我想强制用户注册他们的电子邮件地址DataType.EmailAddress不起作用。
public class RegisterModel
{
[Required]
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
...
}
感谢任何帮助。
答案 0 :(得分:2)
如果您想要验证电子邮件地址,则需要[EmailAddress]
属性(NET 4.5)
[Required]
[Display(Name = "E-mail")]
[EmailAddress] // Add this
public string UserName { get; set; }
或者对于.NET 4.0,您可以使用[RegularExpression]
属性(这个属性来自jquery-validate 1.9.0)
[Required]
[Display(Name = "E-mail")]
[RegularExpression(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$", ErrorMessage="Please enter a valid email adress")]
public string UserName { get; set; }
请注意[DataType]
@Html.EditorFor()
属性用于呈现浏览器使用的type
属性(例如type="email"
)
答案 1 :(得分:0)
您可以使用“EmailAddress”注释:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string UserName { get; set; }
编辑:
对于MVC 4及更低版本,您可以使用正则表达式对电子邮件地址字段进行验证。 点击此处了解更多信息:
http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/