user3396441
user3396441

Reputation: 29

User validation using regular expression

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.

Upvotes: 1

Views: 185

Answers (2)

Mike Brind
Mike Brind

Reputation: 30120

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!");
}

Upvotes: 0

jkone
jkone

Reputation: 76

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!

Upvotes: 1

Related Questions