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

4

11

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.

Liquate answered 27/5, 2011 at 14:21 Comment(1)
Check this Example: codingfusion.com/Post/…Compunction
C
9

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.

Chud answered 27/5, 2011 at 14:22 Comment(3)
Suppose I wanted to write my own attribute such as [Email]. How could I do that and have it produce unobtrusive javascript. Can you point me in the right direction?Liquate
@Dismissile, checkout the Scott Gu blog post. In it he derives from RegularExpressionAttribute and because of this client validation will work automatically because the Regex attribute already registers a jquery adapter.Chud
Cool thanks. I skimmed it but I didn't see that he actually derived it.Liquate
I
11

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; }
Iyeyasu answered 27/5, 2011 at 16:10 Comment(0)
C
9

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.

Chud answered 27/5, 2011 at 14:22 Comment(3)
Suppose I wanted to write my own attribute such as [Email]. How could I do that and have it produce unobtrusive javascript. Can you point me in the right direction?Liquate
@Dismissile, checkout the Scott Gu blog post. In it he derives from RegularExpressionAttribute and because of this client validation will work automatically because the Regex attribute already registers a jquery adapter.Chud
Cool thanks. I skimmed it but I didn't see that he actually derived it.Liquate
W
9

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.

Wistful answered 27/5, 2011 at 14:43 Comment(1)
What Vadim meant to say was that there's a NuGet package now available that includes built-in DataAnnotations for Email, Date, CreditCard and others. Very nice. Project website: dataannotationsextensions.org.Woolgrower
V
0

EmailAddress attribute is built into framework already, no need for Data Annotation Extensions or other logic: Email model validation with DataAnnotations and DataType

Virginiavirginie answered 24/5, 2017 at 4:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.