使用DataAnnotations和DataType进行电子邮件模型验证

lif*_*chi 51 c# email validation asp.net-mvc model

我有以下型号:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    public string Webcode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

必需的验证工作正常.但是当我尝试使用DataType时它没有反应.

这是我的电子邮件控件的剃刀代码:

   @Html.TextBoxFor
          (model => model.Email, 
           new { @style = "width: 175px;", @class = "txtField" }
          ) * 
Run Code Online (Sandbox Code Playgroud)

那么,有人知道答案吗?

TIA

Len*_*rri 116

DataType attribute用于格式化目的,而不是用于验证.

我建议您使用ASP.NET MVC 3 Futures进行电子邮件验证.

示例代码:

[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果你碰巧正在使用.NET Framework 4.5,现在有一个内置的EmailAddressAttribute生活System.ComponentModel.DataAnnotations.EmailAddressAttribute.

  • 但它接受'某些@域'.我想我这次会用正则表达式. (4认同)
  • 因为我们无法给出自定义错误消息。我改用以下方法。[EmailValidation(ErrorMessage = "电子邮件地址已存在")] [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@ [a-z0-9-]+(\\.[a-z0-9]+)*\\.([az]{2,4})$" , ErrorMessage = "电子邮件格式无效。" )] [必需(ErrorMessage = "请输入您的电子邮件地址。"), StringLength(50)] public string Email { get; 放; } (2认同)

jru*_*ell 8

DataAnnotationsExtensions项目有一个电子邮件属性,您可以使用.