0

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*$")]
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Davy
  • 1,043
  • 2
  • 12
  • 21

1 Answers1

-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}$") { }
}
minimalis
  • 1,763
  • 13
  • 19