[英]Why doesn't the Phone data annotation work, even when required?
I've got the [Phone]
data annotation defined on a property in my view model: 我在视图模型的一个属性上定义了
[Phone]
数据注释:
public class ContactModel : BaseModel
{
[Required(ErrorMessage = "Please enter your first and last name.")]
[MaxLength(256, ErrorMessage = "Your name is too long, the maximum is 256 character.")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter your email address.")]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
[MaxLength(256, ErrorMessage = "Your email address is too long, the maximum is 256 character.")]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Phone(ErrorMessage = "Please enter a valid phone number.")]
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please enter your comments or request.")]
[Display(Name = "Comments or Request")]
public string Comments { get; set; }
}
but it doesn't validate the format like the [Email]
annotation does; 但是它无法像
[Email]
注释那样验证格式; even when [Required]
. 即使
[Required]
。 For example, if I enter the text 123
the ModelState.IsValid
is still true
because that attribute isn't validating the input. 例如,如果我输入文本
123
则ModelState.IsValid
仍然为true
因为该属性无法验证输入。 To add insult to injury, nothing is happening client-side like it does with the email address. 更糟的是,客户端没有像电子邮件地址那样发生任何事情。 If I enter an invalid email address I actually get the JavaScript validation - as expected.
如果我输入了无效的电子邮件地址,则实际上可以得到JavaScript验证-如预期的那样。
What's going on? 这是怎么回事?
I'm using Mvc 5.1.0.0 so I've updated to the latest version to ensure it wasn't version specific. 我正在使用Mvc 5.1.0.0,所以我已经更新到最新版本,以确保它不是特定于版本的。
It does, in fact, validate. 实际上,它可以验证。 The problem is that 123 is a valid phone number, somewhere... If you try entering letters, you will notice that validation fails.
问题是123是一个有效的电话号码,在某处...如果尝试输入字母,您会注意到验证失败。 But, if you enter (123) 234-2342 it succeeds...
但是,如果您输入(123)234-2342,它将成功...
This is because it has to work for phone numbers all over the world. 这是因为它必须适用于全世界的电话号码。 It even has to work for internal extensions (which could easily be 2, 3, 4 or 5 digits long).
它甚至必须用于内部扩展(可以很容易地长2、3、4或5位数字)。 Specifically, if you go here:
具体来说,如果您去这里:
http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs
You will see that the regex allows pretty much any numbers. 您会看到正则表达式几乎允许任何数字。 If you want a US Specific Phone validation, then you should probably just use the regex attribute, or develop your own USPhoneAttribute based on this one.
如果要验证“美国专用电话”,则应该只使用regex属性,或基于此属性开发自己的USPhoneAttribute。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.