What is the difference between the [EmailAddress]
and the [DataType(DataType.Email)]
attribute?
What is the difference between the [Phone]
and [DataType(DataType.PhoneNumber)]
attribute?
[EmailAddress]
public string Email { get; set; }
[Phone]
public string Phone { get; set; }
and
[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?
DataType Attribute in ASP.NET MVC Framework enables us to provide the runtime information about the specific purpose of the properties. For example, a property of type string can have various scenarios as it might hold an Email address, URL, or password.
ComponentModel. DataAnnotations) Specifies the minimum and maximum length of characters that are allowed in a data field.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With