Email address validation in C# MVC 4 application: with or without using Regex

This question already has an answer here:

  • Email address validation using ASP.NET MVC data type attributes 6 answers

  • You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example

    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }
    

    Expanding on Ehsan's Answer....

    If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute Class in code.

    private static bool IsValidEmailAddress(string emailAddress)
    {
        return new System.ComponentModel.DataAnnotations
                            .EmailAddressAttribute()
                            .IsValid(emailAddress);
    }
    

    If you are considering REGEX to verify email address then read:

    I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack


    Regex:

    [RegularExpression(@"^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
    

    Or you can use just:

        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
    
    链接地址: http://www.djcxy.com/p/92604.html

    上一篇: Ruby Regex从电子邮件地址中提取域

    下一篇: C#MVC 4应用程序中的电子邮件地址验证:使用或不使用Regex