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

标签 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]

但是它不起作用,为什么?

最佳答案

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

改为使用此属性:

[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));

关于c# - RegexValidator 验证电子邮件,制作标准属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2509360/

相关文章:

c# - 如何在每天的特定时间自动发送电子邮件

magento获取属性集中的可配置属性

c# - unsigned char ** 相当于 c# 中的值,并且必须将返回值写入文件中

c# - 获取 SPFieldCurrency 字段的数值

Php 联系表,一直工作到迁移。警告 : mail() [function. 邮件] : Bad parameters to mail() function, 邮件未发送

c# - 从枚举属性获取枚举

jquery - 如果子元素是 img,则将 rel 属性应用于 <a> - jquery

c# - 初始化属性时的问题

c# - 如何重新创建app.config.exe.config

iphone - 有没有办法限制仅将电子邮件发送到预定义的目的地?