1

Hey guys I am working on a project in webmatrix that requires a user to register there details. The first box is their email address. Basically I need a bit of help nailing down the regular expressions.

Ive got a file called validation.cshtml in main folder with the following function:

@functions {
    public static bool IsValidEmail(string value) 
    { 
        const string expression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; 
        return Regex.IsMatch(value, expression); 
    }
}

Then I call the function in the register.cshtml page, but here is where i am going wrong. I am not sure how to write the function. Here is what I have

if (!Validation.IsMatch(email)) 
{ 
    ModelState.AddError("email", "The Email Address Must contain the @ sign"); 
} 

I have "email" here because this is the variable name for the email textfield.

1
  • Sorry the code came out a bit all over the place! Commented Mar 23, 2014 at 17:19

2 Answers 2

1

If you use MVC there is no need to write your own validation for an emailaddress. Add a Datetype Attribute to your Property in the modelclass.

[DataType(DataType.EmailAddress)]
public string Email { get; set; }

In the view add a validationmessage.

@Html.ValidationMessageFor(x => x.Email)

And that´s it.

Hope that will fit your needs!

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to validate a string to see if it can be used to send emails to, you don't need Regular Expressions. This will do it:

@functions {
    public static bool IsValidEmail(string value) {
        try{
            MailAddress email = new MailAddress(value);
            return true;
        }
        catch(FormatException fex){
            return false;
        }
    }
}

You may need to add

using System.Net.Mail;

to the top of the file.

Functions should be in a cshtml file in the App_Code folder so that they can be used by any file in the site. Otherwise their scope is restricted jut to the file that they are in. If you move your Validation.cshtml file to App_Code (you may need to create that folder first) and rename it to MyValidation.cshtml to prevent collisions with the ValidationHelper class, you call the method lie this:

if(!MyValidation.IsValidEmail(email)){
    ModelState.AddError("email", "BOOOM!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.