gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:42:38 24 4
gpt4 key购买 nike

我想使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com