Reputation: 7504
I'm using jQuery to validate form elements on an MVC form and this is my regular expression to validate zip codes:
^(\d{5})|(\d{5}-\d{4})$
It validates a 5-digit zip code just fine, but the red box around the text box input element remains—er, comes back—when I add a hyphen and 4 more digits.
Why?
Upvotes: 0
Views: 543
Reputation: 7504
When I looked more closely at the generated HTML, I noticed that it has data-val-length-max="9". This is an attribute in the model. I changed it to 10, and voilà!
To allow the validation to work properly and still pass the unformatted digits to the database, I just return this from the getter of the model:
_zip.Replace("-", string.Empty)
Upvotes: 0
Reputation: 272106
The brackets are wrong in the following RegRxp:
^(\d{5})|(\d{5}-\d{4})$
This iIs like saying match ^\d\d\d\d\d
or match \d\d\d\d\d-\d\d\d\d$
. It incorrectly matches 12345x
and x98765-4321
. Use the following instead:
^(\d{5}|\d{5}-\d{4})$
Upvotes: 4