问题描述
[EmailAddress]
和 [DataType(DataType.Email)]
属性之间有什么区别?
What is the difference between the [EmailAddress]
and the [DataType(DataType.Email)]
attribute?
[电话]
和 [DataType(DataType.PhoneNumber)]
属性之间有什么区别?
What is the difference between the [Phone]
and [DataType(DataType.PhoneNumber)]
attribute?
[EmailAddress]
public string Email { get; set; }
[Phone]
public string Phone { get; set; }
和
[DataType(DataType.Email)]
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
这些相同还是有区别?有什么区别?哪个是首选方式?什么时候应该使用?
Are these the same or is there any difference? What is the difference? Which is the preferred way? When should which be used?
推荐答案
DataTypeAttribute
更改< input>
元素的 type
属性由MVC渲染.
DataTypeAttribute
changes the type
attribute of the <input>
elements rendered by MVC.
@David是正确的,因为 EmailAddressAttribute
是从 DataTypeAttribute
派生的,因此使用 [DataType(DataType.Email)]
获得的所有功能也是正确的使用 [EmailAddress]
时显示.这两个属性都会导致MVC呈现HTML < input type ="email">
元素.
@David is right that EmailAddressAttribute
derives from DataTypeAttribute
, so all functionality you get with [DataType(DataType.Email)]
is also present when you use [EmailAddress]
. Both attributes cause MVC to render HTML <input type="email">
elements.
但是, EmailAddressAttribute
在此之上添加了服务器端验证.即如果仅使用 DataTypeAttribute
,则不会进行服务器端验证!您可以轻松地使用每个属性来测试模型.对于它们中的每一个,您都应该获得客户端验证,并且应该不可能使用无效的电子邮件地址提交表单.但是,如果将< input>
元素类型更改为 text
(通过Firebug或诸如此类),则将删除该验证,并将能够提交带有任何内容的表单您喜欢的文字.然后,在提交表单所调用的操作中放置一个断点,并检查 ModelState.IsValid
的值-当您使用 DataTypeAttribute
时,它是 true
.当您使用 EmailAddressAttribute
时,它为 false
.这是因为后者添加了一些基于正则表达式的服务器端验证.
However, EmailAddressAttribute
adds server-side validation on top of that. I.e. there is no server-side validation if you only use DataTypeAttribute
! You can easily test your model with each of those attributes. For each of them, you should get client-side validation and it shouldn't be possible to submit the form with invalid email address. However, if you change the <input>
element type to text
(via Firebug or whatnot), you will remove that validation and will be able to submit the form with whatever text you like. Then, put a breakpoint in the action invoked by submitting the form and examine the value of ModelState.IsValid
- when you use DataTypeAttribute
, it is true
. When you use EmailAddressAttribute
, it is false
. This is because the latter adds some regex-based server-side validation.
结论:您应该使用 EmailAddressAttribute
等,否则,您实际上并没有真正在进行验证,而是依靠客户端来完成验证(Bad Thing™).
Conclusion: you should use EmailAddressAttribute
et al., otherwise you're not really doing the validation on your end and rely on the client to do it (a Bad Thing™).
当然,您也可以使用 DataTypeAttribute
并实现自己的服务器端验证(例如,由于任何原因, EmailAddressAttribute
中的验证都不起作用).
Of course you can also use DataTypeAttribute
and implement your own server-side validation (e.g. because the one in EmailAddressAttribute
doesn't work for you for whatever reason).
这篇关于EmailAddress或DataType.Email属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!