使用 ASP.NET MVC 数据类型属性的电子邮件地址验证 [英] Email address validation using ASP.NET MVC data type attributes

查看:39
本文介绍了使用 ASP.NET MVC 数据类型属性的电子邮件地址验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在验证电子邮件时遇到一些问题.

I have some problems with the validation of a Email.

在我的模型中:

[Required(ErrorMessage = "Field can't be empty")]
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
public string ReceiverMail { get; set; }

在我看来:

<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)

现在,当您将字段留空时,它会正确地向我显示字段不能为空".但是,当您填写无效的电子邮件地址时,例如:fwenrjfw",则表单不会显示电子邮件无效".

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".

如何获取表单以将输入验证为电子邮件地址?我正在寻找这方面的帮助.

How can I get the form to validate the input as an email address? I am looking for some help with this.

推荐答案

如果您使用 .NET Framework 4.5,解决方案是使用位于 System.ComponentModel.DataAnnotations 中的 EmailAddressAttribute.

If you are using .NET Framework 4.5, the solution is to use EmailAddressAttribute which resides inside System.ComponentModel.DataAnnotations.

您的代码应该类似于:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

这篇关于使用 ASP.NET MVC 数据类型属性的电子邮件地址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆