EmailAddressAttribute而无需 [英] EmailAddressAttribute without being required
问题描述
我有一个 [EmailAddress的]
DataAnnotation从.NET 4.5的一个模型属性,它返回一个电子邮件字段不是一个有效的电子邮件地址期间验证错误,当邮件属性为空。
I have a [EmailAddress]
DataAnnotation from .net 4.5 on a model property, which returns a 'The Email field is not a valid e-mail address.' error during validation, when the Email property is empty.
尽管这在技术上是真实的,我本来期望这个空值只能抓到一个 [必需]
注释。
While this is technically true, I would have expected this empty value to only be caught with a [Required]
annotation.
有没有参数,我失去了可以传递给 [EmailAddress的]
注释允许使用空字符串来验证,还是必须回退到使用自定义验证常规EX pression?
Is there any parameter I'm missing which can be passed to the [EmailAddress]
annotation to allow empty strings to validate, or do I have to fall back to using a custom validator regular expression?
推荐答案
没有为 EmailAddressAttribute
没有这样的参数。验证code这个attibute是以下内容:
There is no such parameter for EmailAddressAttribute
. The validation code for this attibute is following:
if (value == null)
{
return true;
}
string input = value as string;
return ((input != null) && (_regex.Match(input).Length > 0));
和正则表达式定义为(会有敌不过空字符串):
And the regex is defined as (there will be no match for empty string):
_regex = new Regex(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
要实现你的目标,你可以创建你可以从 DataTypeAttribute
继承覆盖的IsValid
的方法,所以它会返回真
为空或空字符串,并使用 EmailAddressAttribute
。这应该是这样的:
To achieve your goal you can create your can inherit from DataTypeAttribute
override IsValid
method, so it will return true
for empty or null strings and use instance of EmailAddressAttribute
. This should be something like this:
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
string input = value as string;
var emailAddressAttribute = new EmailAddressAttribute();
return (input != null) && (string.IsNullOrEmpty(input) || emailAddressAttribute.IsValid(input));
}
这篇关于EmailAddressAttribute而无需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!