Can I use my RegularExpression attribute instead of the DataAnnotations one?

时光总嘲笑我的痴心妄想 提交于 2019-12-13 21:54:34

问题


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*$")]

回答1:


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}$") { }
}


来源:https://stackoverflow.com/questions/1483630/can-i-use-my-regularexpression-attribute-instead-of-the-dataannotations-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!