Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating an e-mail address with unobtrusive javascript / MVC3 and DataAnnotations

jQuery Validation makes it simple to validate an email address:

$("someForm").validate({
    rules: {
        SomeField: {
            required: true,
            email: true,
            remote: {
                type: "POST",
                url: "CheckEmail"
            }
        }
    }
});

This makes it so that SomeField is required, must be formatted as an e-mail address and also performs a remote call to the CheckEmail action (check for duplicates).

I like to make things as simple as possible so I can do a lot of the same stuff with Data Annotations:

public class RegisterModel {
    [Required]
    [Remote("CheckEmail", "Home", HttpMethod="POST")]
    public string SomeField { get; set; }
}

Does ASP.net MVC 3 / Data Annotations have a built-in/simple way to validate to make sure the e-mail address is in the correct format?

I would like it to produce unobtrusive javascript if possible.

like image 274
Dismissile Avatar asked May 27 '11 14:05

Dismissile


People also ask

How to validate an email address in JavaScript?

Checkpoints for efficient email validation in JavaScript code: 1 Describe a regular expression to validate an email address 2 If an input value matches regular expressions 3 If it matches, sends the alert saying “email address is valid.” 4 If it does not match, send the alert saying, “email address is invalid.”

How to validate an email at the client side of an application?

The file consists of a JavaScript code required for email validation. Here the regular expressions are used to validate an email at the client-side of an application. If it matches, sends the alert saying “email address is valid.” If it does not match, send the alert saying, “email address is invalid.”

Do real email addresses fail the validation test?

I've seen plenty of real email addresses that would fail this 'validation' test. @Amrita: This is validation, not verification. This is only meant to validate the structure and syntax of the address, it makes no attempt to verify that the address exists, or for that matter, is even routable (as in, the domain actually exists).

What is @email validation?

Email validation is a critical part of validating an HTML form. An email is a string or a subset of ASCII characters separated into two parts by @ symbol. The first part contains personal information while the other contains the domain name at which the email is registered. The personal information part can contain the following ASCII characters:


3 Answers

I think this is the code you are looking for (this is similar to ScottGu's example but also shows the DisplayName in the default error message instead of the property name):

public class EmailAttribute : RegularExpressionAttribute
{
    private const string defaultErrorMessage = "'{0}' must be a valid email address";

    public EmailAttribute() : 
        base("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$")
    { }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(defaultErrorMessage, name);
    }

    protected override ValidationResult IsValid(object value,
                                            ValidationContext validationContext)
    {
        if (value != null)
        {
            if (!base.IsValid(value))
            {
                return new ValidationResult(
                    FormatErrorMessage(validationContext.DisplayName));
            }
        }

        return ValidationResult.Success;
    }
}

Then your model property would look like this:

    [DisplayName("My Email Address")]
    [Email]
    public string EmailAddress { get; set; }
like image 123
Robert Corvus Avatar answered Sep 21 '22 14:09

Robert Corvus


Does ASP.net MVC 3 / Data Annotations have a built-in/simple way to validate to make sure the e-mail address is in the correct format?

Not built-in but you could use a [RegularExpression]. Scott Gu illustrated an example of such regex in a blog post. He wrote a custom EmailAttribute deriving from RegularExpressionAttribute to avoid repeating logic.

like image 26
Darin Dimitrov Avatar answered Sep 21 '22 14:09

Darin Dimitrov


The Data Annotation Extensions library has an [Email] attribute that allows for validating an email address.

There is also a blog post outlining how to use the library.

like image 39
Vadim Lozinskiy Avatar answered Sep 20 '22 14:09

Vadim Lozinskiy