Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

asp.net - EmailAddress or DataType.Email attribute

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...