I know normally you could apply a regular expression to the field, but since these are part of an address block, I assume I need some kind of Javascript to set up this regex. How may I do this so it applies to all addresses in a form?
Question
Question
How can we limit the Zip Code portion of an "Address" Form field to only 5 digits?
asked on May 8, 2015
0
0
Answer
APPROVED ANSWER
replied on May 8, 2015
See if this Javascript is sufficient
$(document).ready (function () { var re = new RegExp("^\\d{5}$"); $('.Postal').on('change', function() { var s = parseNumber($(this).val()); $('p.zipWarning').remove(); if (re.test(s)) { $('.Postal').val(s); $('.Submit').removeAttr('disabled'); } else { $('.Postal').val("0"); $('<p class="zipWarning">Please enter a 5 digit zip code.</p>').insertAfter('.Postal'); $('.Submit').attr('disabled', true); } }); function parseNumber(n) { var f = parseFloat(n); //Convert to float number. return isNaN(f) ? 0 : f; //treat invalid input as 0; } })
If an invalid value is entered in, it will display a message indicating that a 5 digit zip code is needed. I've also added code to disable the submit button if that would be useful. Otherwise, you can just remove the two $('.Submit') lines.
2
0
Replies
replied on May 11, 2015
Gareth,
I use a slightly different method than Alex posted above. I use the jquery.mask.min.js library to apply constraints (masks) to fields. This adds some useful functionality when it comes to phone numbers, SSN, etc. You will obviously need to download the library, then point your javascript at the correct location.
//Field Mask //Must make sure that .getscript is pointing at the correct location - Field must have the phone or zip CSS class $(document).ready (function () { $.getScript('http://YOURCOMPUTERNAME/Forms/js/jquery.mask.min.js', function () { $(".phone input").mask("(999) 999 - 9999"); //Applies a mask of #####-### to the fields with CSS class of zip $(".zip input").mask("99999-999"); }); }); //End Field Mask
-Nate
0
0
replied on May 13, 2015
Thank you both - I will give these a shot and get back to you.
0
0
You are not allowed to follow up in this post.