RegularExpressionAttribute - How to make it not case sensitive for client side validation?
I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.
[RegularExpressionWithOptions(@".+@example\.com", RegexOptions = RegexOptions.IgnoreCase)]
C#
public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }
public RegexOptions RegexOptions { get; set; }
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value as string))
return true;
return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "regexwithoptions"
};
rule.ValidationParameters["pattern"] = Pattern;
string flags = "";
if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
flags += "m";
if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
flags += "i";
rule.ValidationParameters["flags"] = flags;
yield return rule;
}
}
JavaScript
(function ($) {
$.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
options.messages['regexwithoptions'] = options.message;
options.rules['regexwithoptions'] = options.params;
});
$.validator.addMethod("regexwithoptions", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
var reg = new RegExp(params.pattern, params.flags);
match = reg.exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
})(jQuery);
This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators
In C# you can inline some regex options. To specify the option to ignore case you would add (?i)
to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute
and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator
I doubt it; the regex should be vanilla enough to work for both engines.
In any case if it was valid it would look like this:
@"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"
private const String regex = @"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";