我可以使用的DataAnnotations我的一个RegularEx pression属性呢? [英] Can I use my RegularExpression attribute instead of the DataAnnotations one?
本文介绍了我可以使用的DataAnnotations我的一个RegularEx pression属性呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用一个可重复使用的正则表达式类,并使用与MVC中的DataAnnotations。是这样的:
[RegularEx pressionAttribute1(typeof运算(MyRegex))]
这编译,但不会引发错误,如果属性不匹配。
据该标准的所有作品
[RegularEx pression(@^ \ S * \ D +(\。\ D {1,2})?\ S * $)]
解决方案
您可以创建一个自定义的验证属性重新使用常规的前pressions。对于电子邮件验证,你会做这样的事情:
使用System.ComponentModel.DataAnnotations;
公共类EmailAttribute:RegularEx pressionAttribute
{
公共EmailAttribute()
:基地(@(我)^ [A-Z0-9 ._%+ - ] + @ [A-Z0-9 .-] + \ [AZ] {2,4} $?。){}
}
I'm trying to use a reusable regex class and use along with DataAnnotations in MVC. Something like:
[RegularExpressionAttribute1(typeof(MyRegex))]
This compiles but no error is thrown if the property doesn't match.
It all works with the standard
[RegularExpression(@"^\s*\d+(\.\d{1,2})?\s*$")]
解决方案
You can create a custom validation attribute to re-use regular expressions. For email validation you would do something like this:
using System.ComponentModel.DataAnnotations;
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
: base(@"(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$") { }
}
这篇关于我可以使用的DataAnnotations我的一个RegularEx pression属性呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文