views:

116

answers:

1

I would like to validate an email using the RegexValidator, e.g.

[RegexValidator(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$")]

Which works fine, now I want to wrap the attribute so I can store this in one place:

public class EmailAttribute : RegexValidator 
{
    public EmailAttribute()
        : base(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$")
    {
    }
}

So I can use

[EMail]

But it is not working, why?

+2  A: 

You should not validate email addresses using regular expressions.

Instead, use this attribute:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class EmailAddressAttribute : DataTypeAttribute {
    public EmailAddressAttribute() : base(DataType.EmailAddress) { ErrorMessage = "Please enter a valid email address"; }

    public override bool IsValid(object value) {
        if (value == null) return true;
        MailAddress address;
        try {
            address = new MailAddress(value.ToString());
        } catch (FormatException) { return false; }
        return address.Host.IndexOf('.') > 0;    //Email address domain names do not need a ., but in practice, they do.
    }
}

If you want client-side validation for ASP.Net MVC, use this adapter:

public class EmailAddressValidator : DataAnnotationsModelValidator<EmailAddressAttribute> {
    public EmailAddressValidator(ModelMetadata metadata, ControllerContext context, EmailAddressAttribute attribute) : base(metadata, context, attribute) { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
        yield return new ModelClientValidationRegexRule(Attribute.ErrorMessage, 
                     @".+@.+\..+");    //Feel free to use a bigger regex
    }
}

And register it like this:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(EmailAddressValidator));
SLaks
I'm using this in my own code; it works perfectly.
SLaks