Jason King Team : Web Development Tags : Web Development Tips & Tricks

.NET Regular Expression Attributes that can be modified at run time

Jason King Team : Web Development Tags : Web Development Tips & Tricks

An MVC project I’ve been working on recently has several variations depending on the country.   One of these variations is different account number lengths between Australia and New Zealand.   The former has a maximum length of 9 while the latter has a maximum of 10.   To ensure that only valid input is allowed, we use regular expression attributes so that the input is automatically validated on the client and server.

Here’s a simple and tidy bit of code that allows you to extend the .NET RegularExpressionAttribute so that the regex can be modified at run time (based on some config setting).

 

public class SiteRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public SiteRegularExpressionAttribute(string regexKey, string errorMessageKey, string defaultErrorMessage)
            : base(ConfigurationManager.AppSettings[regexKey])
        {
            this.ErrorMessage = ConfigurationManager.AppSettings[errorMessageKey] ?? defaultErrorMessage;
        }

        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRegexRule(FormatErrorMessage(metadata.GetDisplayName()), Pattern);
        }
    }

Now you can update the property in your view model to use the new SiteRegularExpressionAttribute:

  

[SiteRegularExpression("Regex.Pattern.AccountNumber", "Regex.Message.AccountNumber", "Account number must only contain digits.")]
        public string SendingAccountNumber { get; set; }

If you prefer not to fill your appSettings section with lots of regular expressions and error messages you could build a custom config section or a settings provider in your code.