简体   繁体   English

.Net mvc4中的电子邮件验证

[英]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 目前,我正在使用以下代码进行电子邮件验证,但它确实验证了dsgf @ g邮件ID,请帮助我

[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. EmailAddress属性会将dsgf@g标记为有效,因为它是一个完全有效的电子邮件地址,因此该方法没有任何问题。 Consider the example username@localhost for example. 例如,考虑示例username@localhost

If it is not suits you then you can use regular expression ti set your own rule for validation. 如果不合适,则可以使用正则表达式ti设置自己的验证规则。 Try to use 'RegularExpression' attribute instead, something like: 尝试改用'RegularExpression'属性,例如:

[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) 电子邮件地址现在可以包含ä,ö,ü,à等字符,这可能很难匹配正确的字符..如果您真的想使用正则表达式对其进行验证,则可以采用RFC822标准:在这里找到: http : //www.ex-parrot.com/pdw/Mail-RFC822-Address.html (对此很有趣-不想发布,它太长了)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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