Anmar Al Shammari
Anmar Al Shammari

Reputation: 39

ZipCode Validation Format nnnnn-nnnn

ZipCode Validation Format nnnnn-nnnn. When "-" entered by the user, it has been counted as a digit and it would take out from the max digits i made which is 9 and since the user enters"-" it will allow only 8. How I can skip "-" not to be digit and put in the right enter code here

function formatZipCode(value) {
    value = value.replace(/[^\/\d]/g,'');
    var Z = /(\d{5})(\d)/;
    if (value != undefined && value != '') {
        return value = value.replace(Z, '$1' + '-' + '$2');;
    }
    else {
        return value;
    }
};

Upvotes: 2

Views: 1177

Answers (2)

zer00ne
zer00ne

Reputation: 43880

If it's a HTML form the user inputs into, then you can use it to validate zip codes by using:

  • <input type='number'> - Eliminates letters and symbols
  • min and max attributes - Enforces a range
  • <input type='submit'> - Allows built in validation of <form>

Added additional function to validate digits

First input must be 10000 to 99999

AND

Second input must be 1000 to 9999

SNIPPET

/* Ensures input is 5 and 4 digits by
|| disabling submit button when 
|| requirements are not met.
*/
function digits(num1, num2) {
  var n1 = num1.length;
  var n2 = num2.length;
  if (n1 === 5 && n2 === 4) {
    zip['submit'].disabled = false;
  } else {
    zip['submit'].disabled = true;
  }
}
input {
  font: inherit
}

#z4 {
  width: 6ch;
}

#z5 {
  width: 7ch;
}

fieldset {
  width: 13em;
}

legend,
[type=submit] {
  font-variant: small-caps;
}
<!--
Ensures input is within 10000 - 99999 and
1000 - 9999 by invalidating onsubmit
-->
<form id='zip' name='zip' action='http://httpbin.org/post' method='post' onchange='digits(z5.value, z4.value)'>
  <fieldset>
    <legend>Zipcode</legend>
    <input id='z5' name='z5' type='number' size='5' value='00000' min='10000' max='99999'>-<input id='z4' name='z4' type='number' size='4' value='0000' min='1000' max='9999'>
    <input type='submit' id='submit' disabled>
  </fieldset>
</form>

Upvotes: 1

Rafael Kennedy
Rafael Kennedy

Reputation: 1004

I would use something like the following:

var z = /(\d{5})-?(\d{4})/
value = value.replace(z,"$1-$2")

the question mark after the hyphen indicates zero or one hyphens.

Upvotes: 1

Related Questions