C# 使用 ASP.NET MVC 数据类型属性的电子邮件地址验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16712043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Email address validation using ASP.NET MVC data type attributes
提问by Java Afca
I have some problems with the validation of a Email.
我在验证电子邮件时遇到了一些问题。
In my Model:
在我的模型中:
[Required(ErrorMessage = "Field can't be empty")]
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
public string ReceiverMail { get; set; }
In my view:
在我看来:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@Html.TextBoxFor(m => m.ReceiverMail, new { @placeholder="E-mail"}) <br />
@Html.ValidationMessageFor(m => m.ReceiverMail)
Now it is correctly showing me "Field can't be empty" when you leave the field empty. But when you fill in an invalid email address like: "fwenrjfw" then the form does not say "E-mail is not valid".
现在,当您将字段留空时,它会正确地向我显示“字段不能为空”。但是,当您填写无效的电子邮件地址时,例如:“fwenrjfw”,则表单不会显示“电子邮件无效”。
How can I get the form to validate the input as an email address? I am looking for some help with this.
如何获取表单以将输入验证为电子邮件地址?我正在寻找这方面的帮助。
回答by Alexander Imra
You need to use RegularExpression Attribute, something like this:
您需要使用 RegularExpression 属性,如下所示:
[RegularExpression("^[a-zA-Z0-9_\.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
And don't delete [Required] because [RegularExpression] doesn't affect empty fields.
并且不要删除 [Required] 因为 [RegularExpression] 不影响空字段。
回答by hazimdikenli
Try Html.EditorForhelper method instead of Html.TextBoxFor.
尝试Html.EditorFor辅助方法而不是Html.TextBoxFor.
回答by Peter Smith
I use MVC 3. An example of email address property in one of my classes is:
我使用 MVC 3。我的一个类中的电子邮件地址属性示例是:
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[Email(ErrorMessage = "The email address is not valid")]
public string Email { get; set; }
Remove the Requiredif the input is optional. No need for regular expressions although I have one which covers all of the options within an email address up to RFC 2822 level (it's very long).
Required如果输入是可选的,则删除。不需要正则表达式,尽管我有一个涵盖电子邮件地址中所有选项的正则表达式,最高可达 RFC 2822 级别(它很长)。
回答by Shittu Joseph Olugbenga
If you are using .NET Framework 4.5, the solution is to use EmailAddressAttributewhich resides inside System.ComponentModel.DataAnnotations.
如果您使用的是 .NET Framework 4.5,解决方案是使用EmailAddressAttributewhich 驻留在System.ComponentModel.DataAnnotations.
Your code should look similar to this:
您的代码应该类似于:
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
回答by mcfea
if you aren't yet using .net 4.5:
如果您还没有使用 .net 4.5:
/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
static EmailAnnotation()
{
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
}
/// <summary>
/// from: http://stackoverflow.com/a/6893571/984463
/// </summary>
public EmailAnnotation()
: base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
+ "@"
+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }
public override string FormatErrorMessage(string name)
{
return "E-mail is not valid";
}
}
Then you can do this:
然后你可以这样做:
public class ContactEmailAddressDto
{
public int ContactId { get; set; }
[Required]
[Display(Name = "New Email Address")]
[EmailAnnotation] //**<----- Nifty.**
public string EmailAddressToAdd { get; set; }
}
回答by Tiramonium
Scripts are usually loaded in the end of the html page, and MVC recommends the using of bundles, just saying. So my best bet is that your jquery.validatefiles got altered in some way or are not updated to the latest version, since they do validate e-mail inputs.
脚本通常在html页面的最后加载,MVC推荐使用bundles,只是说一下。所以我最好的办法是你的jquery.validate文件以某种方式被改变或没有更新到最新版本,因为它们确实验证了电子邮件输入。
So you could either update/refresh your nuget package or write your own function, really.
因此,您可以更新/刷新您的 nuget 包或编写自己的函数,真的。
Here's an example which you would add in an extra file after jquery.validate.unobtrusive:
这是一个示例,您将在以下文件中添加一个额外的文件jquery.validate.unobtrusive:
$.validator.addMethod(
"email",
function (value, element) {
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
"This e-mail is not valid"
);
This is just a copy and paste of the current jquery.validateRegex, but this way you could set your custom error message/add extra methods to fields you might want to validate in the near future.
这只是当前正则jquery.validate表达式的复制和粘贴,但通过这种方式,您可以设置自定义错误消息/向您可能希望在不久的将来验证的字段添加额外的方法。
回答by Kuganrajh Rajendran
[Required(ErrorMessage = "Please enter Social Email id")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
回答by Kalyani Rathore
Used the above code in MVC5 project and it works completely fine with the validation error.Just try this code
在 MVC5 项目中使用了上面的代码,它在验证错误的情况下完全正常工作。试试这个代码
[Required]
[Display(Name = "Email")]
[EmailAddress]
[RegularExpression(@"^([A-Za-z0-9][^'!&\#*$%^?<>()+=:;`~\[\]{}|/,?@ ][a-zA-z0-
9-._][^!&\#*$%^?<>()+=:;`~\[\]{}|/,?@ ]*\@[a-zA-Z0-9][^!&@\#*$%^?<>
()+=':;~`.\[\]{}|/,? ]*\.[a-zA-Z]{2,6})$", ErrorMessage = "Please enter a
valid Email")]
public string ReceiverMail { get; set; }

