Etienne
Etienne

Reputation: 41

ASP.NET MVC 2 - Multiple Regex on a property

I would like to know if a way exists in asp.net mvc 2, to have multiple regular expression on a proprety. For example :

[RegularExpression("[^0-9]", ErrorMessageResourceName = ValidationMessageResourceNames.OnlyDigits, ErrorMessageResourceType = typeof(ValidationMessages))]
[RegularExpression("[^<>]{2,}", ErrorMessageResourceName = ValidationMessageResourceNames.SpecialCharErrorCreateAccount, ErrorMessageResourceType = typeof(ValidationMessages))]
public string City { get; set; }

The target here, is two have two specific error messages, one for the digits and one other for the special Chars and the fact that the min lenght must be 2 chars.

Thanks in advance for the help, or experience.

Etienne.

Upvotes: 4

Views: 7354

Answers (3)

Sohel Pathan
Sohel Pathan

Reputation: 365

Try this,

[RegularExpression("[^0-9]|[^<>]{2,}", ErrorMessageResourceName = ValidationMessageResourceNames.OnlyDigits, ErrorMessageResourceType = typeof(ValidationMessages))]
public string City { get; set; }

Here '|' has been used as OR condition to match

Upvotes: -1

Robert Koritnik
Robert Koritnik

Reputation: 105029

Change attribute usage with a custom class

The best solution is of course to create a custom attribute that inherits from RegularExpressionAttribute but sets different attribute usage settings. The main setting is AllowMultiple that you need to set to true.

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=true)]
public class MultiRegularExpressionAttribute: RegularExpressionAttribute
{
    ...
}

You would use this attribute just like you use the existing RegularExpressionAttribute, but you'd have the ability to put multiple of them on the same property.

Upvotes: 1

frennky
frennky

Reputation: 13934

Something like this:

    public class DigitsAttribute : RegularExpressionAttribute
    {
        public DigitsAttribute()
            : base("[^0-9]")
        {
        }    
    }

    public class SpecialCharsAttribute : RegularExpressionAttribute
    {
        public SpecialCharsAttribute()
            : base("[^<>]{2,}")
        {
        }
    }

Use:

[Digits]
[SpecialChars]
public string City { get; set; }

Upvotes: 5

Related Questions