RegexValidator验证电子邮件,制作标准属性

时间:2010-03-24 16:17:35

标签: c# email attributes

我想使用RegexValidator验证电子邮件,例如

[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]$")]

哪个工作正常,现在我想包装属性,以便我可以将它存储在一个地方:

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]$")
    {
    }
}

所以我可以使用

[EMail]

但它不起作用,为什么?

1 个答案:

答案 0 :(得分:10)

您不应使用正则表达式验证电子邮件地址。

相反,请使用此属性:

[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.
    }
}

如果您想要ASP.Net MVC的客户端验证,请使用此适配器:

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
    }
}

并按照以下方式注册:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(EmailAddressValidator));