Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of Datatype.EmailAddress in asp/.net/mvc

I have a Account Model in which I am using Email Address as Username

public class RegisterModel
    {
        [Required]
        [Display(Name = "Email Address")]
        [DataType(DataType.EmailAddress)]
        public string UserName { get; set; }

I have designed a custom class to verify email. But I recently noticed that the DataType.EmailAddress. I tried to use this Datatype as shown in code above to check if I can validate the Username without my Custom Class but it fails. So my question is how is this DataType useful in .NET. It seems to be doing nothing on my Registration Form.

Edit: It dosent even validate against a regex. For example Username: SS, ssssss, tttt, etc all pass off as valid emails.

Edit: People I have a class to validate email in the code behind. I know hat are the complexities of validating Emails. I am not asking how to validate email. I am just asking about the uses of this datatype.

like image 283
Flood Gravemind Avatar asked Oct 17 '13 11:10

Flood Gravemind


2 Answers

So, you are asking what this data type does not why isn't it validating, correct? Per the MSDN, DataType attributes are used primarily for formatting and not validation (which you have learned). What this attribute should do, is when using the Html.DisplayFor() helper, render the field as a clickable hyperlink.

@Html.DisplayFor(x=>x.UserName)

Renders

<a href="mailto:{0}">{0}</a>

Additionally, as pointed out by Zhaph in the comments below, using it in the Html.EditorFor() will generate an HTML 5 email input, which looks something like this:

<input type="email".../>

From MSDN

The following example uses the DataTypeAttribute to customize the display of EmailAddress data field of the customer table in the AdventureWorksLT database. The e-mail addresses are shown as hyperlinks instead of the simple text that ASP.NET Dynamic Data would have inferred from the intrinsic data type.

like image 77
Tommy Avatar answered Sep 21 '22 14:09

Tommy


DataType alone will not trigger any server-side validation. But, since MVC 4 using DataType.EmailAddress will make the HTML input use type="email", which in turn makes jQuery Validation perform Regex validation on the client.

.NET 4.5 introduced the [EmailAddress] attribute, a subclass of DataTypeAttribute. By using [EmailAddress] you get both client and server side validation.

like image 29
Max Toro Avatar answered Sep 20 '22 14:09

Max Toro