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

前端 未结 4 1832
遇见更好的自我
遇见更好的自我 2020-12-16 22:39

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

public class RegisterModel
    {
        [Required]
        [Display(Name = \"Email Add         


        
相关标签:
4条回答
  • 2020-12-16 23:07

    you can use the EmailAddress data annotation or the regex to solve this issue. Date type is used to tell the html helper to render the html for the view.

    [EmailAddress]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Must be a valid Email Address")]
    
    0 讨论(0)
  • 2020-12-16 23:17

    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.

    0 讨论(0)
  • 2020-12-16 23:25

    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.

    0 讨论(0)
  • 2020-12-16 23:30

    Datatype.Emailaddress derives from DataTypeAttribute and adds client-side e-mail validation you also need to set <% Html.EnableClientValidation(); %> in your corresponding view.

    Alternatively you could use the DataAnnotations library by using EmailAddress (This performs server side validation)

    using System.ComponentModel.DataAnnotations; 
    
        [Required]
        [EmailAddress]
        public String Email { get; set; }
    

    This is the regex to validate Email address

    [Required(ErrorMessage="Email is required")]
    [RegularExpression(@"[A-Za-z0-9._%+-]+[A-Za-z0-9.-]+\.[A-Za-z] {2,4}",
    public String Email {get; set;}
    

    You can also create custom email validation Attribute.

    http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

    0 讨论(0)
提交回复
热议问题