RegexValidator for checking emails, creating a standard attribute

I would like to check the email with a RegexValidator, for example

[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 in order to save it 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]$")
    {
    }
}

Therefore i can use

[EMail]

But it does not work, why?

+3
source share
1 answer

You cannot validate email addresses using regular expressions.

Use this attribute instead:

[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 to check on the client side 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 as follows:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(EmailAddressValidator));
+10
source

Source: https://habr.com/ru/post/1738359/


All Articles