I have an asp.net mvc model which uses a RegularExpressionAttribute on zip code and phone fields, and jquery.maskedinput on the inputs (v1.4.1 from Josh Bush). There is no Required attribute.
I am applying masks to the inputs with a call that looks like this:
$form.find('.zip-mask').mask('99999?-9999');
Form validation works fine. However, if I tab away from one of these masked regex inputs and leave the field empty jquery validation gives the input the bright red outline which indicates invalid. I'd like to prevent that from occurring.
I can see where the problem happens. I'm using jquery.validate version 1.16.0. In jquery.validate.unobtrusive.js line 342 this line of code adds the regex validation method:
$jQval.addMethod("regex", function (value, element, params) {
This method fires both on the focusout event and when the form validates. When it fires on focusout, and the input is empty, the "value" parameter contains the zip or phone mask (i.e. "_____?-____" or "(_) _-____"). Since this mask obviously does not meet the regex it returns false and I get that red bar around the input.
When it fires on form validation and the input is empty the "value" parameter is an empty string, and the method returns true, so the form saves successfully.
To sum up: form validation works, because when the form validates the "value" parameter is an empty string, but focusout validation fails, because on focusout the "value" parameter is the mask.
Is there any way to stop the input from passing the mask in the "value" parameter when the input is empty and focusout regex validation occurs?
The answer, per Stephen Muecke's suggestion, is to simply tack OR conditions to the end of each regex, so the two regular expressions now look like this:
The zip code regex needs two OR conditions because zip codes can be 5 or 9 digits. The first OR handles 5-digit zips and the partial mask, the other handles empty inputs, which is the entire mask.