DataTypeAttribute
changes the type
attribute of the <input>
elements rendered by MVC.
@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.
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.
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™).
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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…