使用不显眼的 javascript / MVC3 和 DataAnnotations 验证电子邮件地址
jQuery 验证使验证电子邮件地址变得简单:
$("someForm").validate({
rules: {
SomeField: {
required: true,
email: true,
remote: {
type: "POST",
url: "CheckEmail"
}
}
}
});
这使得 SomeField 是必需的,必须格式化为电子邮件地址,并且还执行对 CheckEmail 操作的远程调用(检查重复项)。
我喜欢让事情尽可能简单,这样我就可以使用数据注释做很多相同的事情:
public class RegisterModel {
[Required]
[Remote("CheckEmail", "Home", HttpMethod="POST")]
public string SomeField { get; set; }
}
Does ASP.net MVC 3 / Data Annotations have abuilt-in/simple way to validate to make certain the e-mail address格式正确吗?
如果可能的话,我希望它能生成不引人注目的 JavaScript。
jQuery Validation makes it simple to validate an email address:
$("someForm").validate({
rules: {
SomeField: {
required: true,
email: true,
remote: {
type: "POST",
url: "CheckEmail"
}
}
}
});
This makes it so that SomeField is required, must be formatted as an e-mail address and also performs a remote call to the CheckEmail action (check for duplicates).
I like to make things as simple as possible so I can do a lot of the same stuff with Data Annotations:
public class RegisterModel {
[Required]
[Remote("CheckEmail", "Home", HttpMethod="POST")]
public string SomeField { get; set; }
}
Does ASP.net MVC 3 / Data Annotations have a built-in/simple way to validate to make sure the e-mail address is in the correct format?
I would like it to produce unobtrusive javascript if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这是您正在寻找的代码(这与 ScottGu 的示例类似,但也在默认错误消息中显示 DisplayName 而不是属性名称):
那么您的模型属性将如下所示:
I think this is the code you are looking for (this is similar to ScottGu's example but also shows the DisplayName in the default error message instead of the property name):
Then your model property would look like this:
不是内置的,但您可以使用
[RegularExpression]
。 Scott Gu 在 中说明了此类正则表达式的示例博客文章。他编写了一个派生自RegularExpressionAttribute
的自定义EmailAttribute
以避免重复逻辑。Not built-in but you could use a
[RegularExpression]
. Scott Gu illustrated an example of such regex in a blog post. He wrote a customEmailAttribute
deriving fromRegularExpressionAttribute
to avoid repeating logic.数据注释扩展库有一个
[Email]
属性,允许验证电子邮件。还有一篇博客文章 概述如何使用该库。
The Data Annotation Extensions library has an
[Email]
attribute that allows for validating an email address.There is also a blog post outlining how to use the library.
EmailAddress 属性已内置到框架中,不需要数据注释扩展或其他逻辑:使用 DataAnnotations 和 DataType 验证电子邮件模型
EmailAddress attribute is built into framework already, no need for Data Annotation Extensions or other logic: Email model validation with DataAnnotations and DataType