如何为 MVC 创建自定义验证属性
我想为 MVC2 的电子邮件地址创建一个自定义验证属性,该属性不是从 RegularExpressionAttribute 继承,但可以在客户端验证中使用。有人能指出我正确的方向吗?
我尝试了这样简单的事情:
[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
public EmailAddressAttribute( )
: base( Validation.EmailAddressRegex ) { }
}
但它似乎对客户不起作用。但是,如果我使用 RegularExpression(Validation.EmailAddressRegex)] 它似乎工作正常。
I'd like to create a custom validation attribute for MVC2 for an email address that doesn't inherit from RegularExpressionAttribute but that can be used in client validation. Can anyone point me in the right direction?
I tried something as simple as this:
[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
public EmailAddressAttribute( )
: base( Validation.EmailAddressRegex ) { }
}
but it doesn't seem to work for the client. However, if I use RegularExpression(Validation.EmailAddressRegex)] it seems to work fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要为新属性注册适配器才能启用客户端验证。
由于RegularExpressionAttribute已经有一个适配器,即RegularExpressionAttributeAdapter,因此您所要做的就是重用它。
使用静态构造函数将所有必要的代码保留在同一个类中。
有关更多信息,请查看这篇文章,解释完整的过程。
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-验证.aspx
You need to register an adapter for the new attribute in order to enable client side validation.
Since the RegularExpressionAttribute already has an adapter, which is RegularExpressionAttributeAdapter, all you have to do is reuse it.
Use a static constructor to keep all the necessary code within the same class.
For more information checkout this post explaining the complete process.
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
CustomValidationAttribute 类 MSDN 页面 现在有一些例子。 Phil Haacked 的帖子已过时。
The CustomValidationAttribute Class MSDN page has a few examples on it now. The Phil Haacked post is out of date.
查看这篇文章中的通用从属属性验证器
Look at the universal Dependent Property Validator in this article
您是否尝试过使用数据注释?
这是我的注释项目
使用 System.ComponentModel.DataAnnotations;
这是在我的模型项目中
这是我的控制器
您需要谷歌 DataAnnotations,因为您需要获取项目并编译它。我愿意这么做,但我需要离开这里很长一段时间。
希望这有帮助。
编辑
通过快速谷歌发现了这个。
Have you tried using Data Annotations?
This is my Annotations project
using System.ComponentModel.DataAnnotations;
This is in my Models project
This is my controller
You'll need to google DataAnnotations as you need to grab the project and compile it. I'd do it but I need to get outta here for a long w/end.
Hope this helps.
EDIT
Found this as a quick google.