我有一个帐户模型,其中我使用电子邮件地址作为用户名
public class RegisterModel
{
[Required]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
我设计了一个自定义类来验证电子邮件。但我最近注意到 DataType.EmailAddress
。我尝试使用上面代码中所示的此数据类型来检查我是否可以在没有自定义类的情况下验证用户名,但它失败了。所以我的问题是这个 DataType 在 .NET
中有什么用。它似乎在我的注册表上什么也没做。
编辑:它甚至不针对正则表达式进行验证。例如,用户名:SS、ssssss、tttt 等
都被当作有效电子邮件发送。
Edit: People 我有一个类可以在后面的代码中验证电子邮件。我知道验证电子邮件的复杂性。我不是在问如何验证电子邮件。我只是问这个数据类型的用途。
最佳答案
所以,您问的是这种数据类型没有什么,为什么不验证,对吗?根据 MSDN,DataType 属性主要用于格式化而不是验证(您已经了解到)。这个属性应该做的是,在使用 Html.DisplayFor()
帮助程序时,将字段呈现为可点击的超链接。
@Html.DisplayFor(x=>x.UserName)
渲染
<a href="mailto:{0}">{0}</a>
此外,正如 Zhaph 在下面的评论中指出的那样,在 Html.EditorFor()
中使用它会生成一个 HTML 5 电子邮件输入,看起来像这样:
<input type="email".../>
来自 MSDN
The following example uses the DataTypeAttribute to customize the display of EmailAddress data field of the customer table in the AdventureWorksLT database. The e-mail addresses are shown as hyperlinks instead of the simple text that ASP.NET Dynamic Data would have inferred from the intrinsic data type.
关于c# - 在 asp/.net/mvc 中使用 Datatype.EmailAddress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19425916/