I have a string that I use for client side validation:
private const String regex = @"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";
I use this string in my [RegularExpression(regex, ErrorMessage = "invalid")]
attribute.
I know that the /i
flag for a Javascript regex is used to make it case insensitive, but just tacking it on to the end of my regex (i.e. @"^....$/i"
isn't working - the regex validation fails completely, regardless of what is entered (valid or not).
What am I missing?
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 theRegularExpressionAttribute
and if it handles translation for client-side. From my experience with ASP.NET'sRegularExpressionValidator
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 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.
C#
JavaScript
This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators