简体   繁体   中英

Email Validation in .Net mvc4

Currently I am using following code for email validation but it does validate the dsgf@g mail id please help me

[Required(ErrorMessage = "Please Enter Email Id")]
[Display(Name = "Email-Id")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }

EmailAddress attribute will mark as valid the dsgf@g because it is a completely valid email address, so there is nothing wrong with that method. Consider the example username@localhost for example.

If it is not suits you then you can use regular expression ti set your own rule for validation. Try to use 'RegularExpression' attribute instead, something like:

[RegularExpression("^[^@\s]+@[^@\s]+(\.[^@\s]+)+$", ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }

or

[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 = "Invalid Email Address")]
public string Cust_Email { get; set; }

the email is completely valid.

if you want to validate, simply don't use regex for validation. Send him a code to this email-address that he has to enter. email-addresses can now contain characters like ä,ö,ü,à,... this could be really difficult to match the correct one.. if you really want to validate it using regex you could take the RFC822 standard then: you will find here: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html (have fun with this - didn't want to post, it's too long)

What about an extension method.

    public static bool IsValidEmail(this string email)
{
    bool rt = false;
    try
    {
        var mail = new System.Net.Mail.MailAddress(email);
        rt = mail.Host.Contains(".");
    }
    catch { }
    return rt;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM