EmailAttribute for validation using data annotations in MVC 3

Here we create an email validation attribute. By implementing the IClientValidatable interface (which will enable the Unobtrusive javascript validation) & inheriting from RegularExpressionAttribute.

    public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
        public EmailAttribute()
            : base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            var errorMessage = FormatErrorMessage(metadata.GetDisplayName());

            yield return new EmailValidationRule(errorMessage);

    public class EmailValidationRule : ModelClientValidationRule
        public EmailValidationRule(string errorMessage)
            ErrorMessage = errorMessage;
            ValidationType = "email";

Then tie your validator to the model, it will validate both client & server side.



public string Email { get;set; }


It requires the web.config settings to enable client validations.

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s