Search code examples
c#asp.net-mvc-3data-annotationsunobtrusive-javascriptunobtrusive-validation

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.


Solution

  • 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.