I am trying to understand what are the main differecnes between using
[DataType(DataType.EmailAddress)]
& [EmailAddress]
.
inside a model class:-
public class MYViewModel {
[DataType(DataType.EmailAddress)] OR [EmailAddress]
public string Email { get; set; }
i did a test and the two attributes will do the following:-
will prevent users from adding invalud email address
will display the value as "EmailTo:..."
but i can not find any differences in respect to the functionality , of course if i use html.TextboxFor
then the Datatype
will not have any effect, while if i use html.EditorFor
then the Datatype data annotation will work,, but i am talking about the differences in respect to the technical implementation ?
Hope this clarifies...
As you noted, DataType
attributes are primarily used for formatting, not validation. The reason it seems to work is:
@Html.EditorFor
renders the HTML5 <input type="email" ....
which defers to the client/browser to do validation. If the browser complies, then client side validation occurs. It will "work" because the client validated it for you (this is not server side validation however)You can test it by changing @Html.EditorFor
to @Html.TextBoxFor
in your view, which will render the input field as <input type="text" ...>
(a standard text input field, not HTML5 email
).
Given a model with something like this:
public class User
{
[Required(ErrorMessage = "Email must be provided")]
[DataType(DataType.EmailAddress, ErrorMessage = "this doesn't do email format validation")]
[EmailAddress(ErrorMessage = "Not a valid Email")] //Comment un-comment to see effect
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Name must be provided")]
public string Name { get; set; }
}
A view using @Html.TextBoxFor
instead of @Html.EditorFor
to take out HTML5 client side validation in your test:
@Html.TextBoxFor(model => model.EmailAddress,....
And a controller like so:
public ActionResult CheckUser(User user)
{
ViewBag.Foo = string.Empty;
if(Request.HttpMethod == HttpMethod.Post.ToString())
{
ViewBag.Foo = ModelState.IsValid ? "User Model validated" : "Failed Model Validation";
}
return View();
}
If you:
[EmailAddress]
attribute, leaving only [DataType(DataType.EmailAddress)]
your model is valid with any text (no email format validation)
"Not a valid Email"
error message is displayedHth...
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