Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmailAddress or DataType.Email attribute

Tags:

asp.net

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?

like image 777
Fred Avatar asked Sep 23 '14 11:09

Fred


People also ask

What is data type in MVC?

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.

What is System ComponentModel DataAnnotations?

ComponentModel. DataAnnotations) Specifies the minimum and maximum length of characters that are allowed in a data field.


1 Answers

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).

like image 169
Jakub Januszkiewicz Avatar answered Oct 16 '22 06:10

Jakub Januszkiewicz