由网友(待我强大我将扫遍所有零食)分享简介:我试图用一个可重复使用的正则表达式类,并使用与MVC中的DataAnnotations。是这样的:[RegularEx pressionAttribute1(typeof运算(MyRegex))]这编译,但不会引发错误,如果属性不匹配。 据该标准的所有作品[RegularEx pression(@^ \ S * \ D...
我试图用一个可重复使用的正则表达式类,并使用与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}$") { }
}
相关推荐
最新文章