I have created the following custom RegularExpressionAttribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
pu
Here's another approach from How to create custom validation attribute for MVC, which is adapted from this article on ASP.NET MVC Custom Validation:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class AlphaNumericAttribute: RegularExpressionAttribute
{
private const string pattern = "^[-A-Za-z0-9]+$";
public AlphaNumericAttribute() : base(pattern)
{
// necessary to enable client side validation
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(AlphaNumericAttribute),
typeof(RegularExpressionAttributeAdapter));
}
}
By using RegisterAdapter, you can leverage the integrations that already exist for regular expressions for your own inherited type.