What are the differences between [DataType (DataType.EmailAddress)] and [EmailAddress]

I am trying to understand what are the main differences between using [DataType(DataType.EmailAddress)]

and [EmailAddress]

.

inside the model class: -

public class MYViewModel {
[DataType(DataType.EmailAddress)] OR [EmailAddress]
public string Email { get; set; }

      

I ran the test and two attributes will do the following: -

  • will not allow users to add an invalid email address

  • will display the value as "EmailTo: ..."

but i can't find any difference in functionality, of course if i use html.TextboxFor

then Datatype

won't have any effect, and if i use html.EditorFor

then datatype data annotation will work but i'm talking about differences in technical implementation?

+3


source to share


1 answer


Hope this clears up ...

As you noted, attributes DataType

are mostly used for formatting, not validation. The reason it works :

  • @Html.EditorFor

    renders HTML5 <input type="email" ....

    which favors the client / browser for validation. If the browser complies, then client-side validation is performed. It will work because the client confirmed it for you (this is not a server side validation )

You can test it out by changing @Html.EditorFor

to @Html.TextBoxFor

in your view, which will render the input field as <input type="text" ...>

(standard text input field, not HTML5 email

).


Test example

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; }
}

      



View using @Html.TextBoxFor

instead @Html.EditorFor

to render HTML5 client side validation in your test:

@Html.TextBoxFor(model => model.EmailAddress,....

      

And a controller like this:

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:

  • comment [EmailAddress]

    attribute, leaving only [DataType(DataType.EmailAddress)]

    your model valid with any text (no email format validation)
    • if you put "foo" your model is "valid" no error message.
  • leave it you will get a server side email format confirmation
    • if you put "foo" it will crash and give an error message "Not a valid Email"

Hth ...

+3


source







All Articles