ZIP Code (US Postal Code) validation

ZIP Code (US Postal Code) validation
0

#1

function formatZipCode(value) {

 value = value.replace(/[^\/\d]/g, '');
 var z = /(\d{5})-?(\d{4})/
 if (value != undefined && value != '') {
 return value = value.replace(z, "$1-$2")

      } else {
     return value;
   }

};

Zip code allows user to enter 10 digits and system displays as 5digits - 5digits(11 characters) which are incorrect

What I would like Zip code -maximum character needs to be 10 characters including the hyphen.

What I have so far


#2

What do you want the function to return called with the following (something shorter than 10 digits)?

formatZipCode('2363-32') 

#3

Hi, Thank you for your reply. Well, I need the hyphen to be placed in the right place either or the user enter the hyphen and at the same time the max digits would be 10. When I enter numbers only such as 1234567890, the hyphen will show up in the middle and it would be 11 digits.

If I enter 12-3456789 (Lets assume the user enters that) it will be 12345-6789 which is perfect. Could you please help?


#4

I understand what you want, but what do you want it to look like if 2363-32 is entered?

Should it convert it to 23633-2?


#5

No, it needs to be a 9 digits U.S Zip Code. nnnnn-nnnn. The minimum needs to be entered is 9 digits. For your example they can’t enter less than 9 digits.


#6

So it sounds as if your formatZipCode function will do more than just insert a hyphen. So if someone enters 23633-2, you want it to return false, so some other function can return a message? I guess I need to see the full form with html and other javascript which works with it.


#7

Thanks a lot again. I already sat that up in terms of error messages and inline error messages.

I just need when user enters 10 digits and only numbers, the last digit will be trimmed and the hyphen will be inserted as nnnnn-nnnn. I guess i need an if statement, but the triming part under the condition user enters 10 digits and only numbers.

otherwise, which would be the users enters the hyphen, it is already taken care of.

Appreciate your help a lot!


#8

find a good service with postal code


#9

Well you can take as example this service https://worldpostalcode.com/ . It’s a great guide for all postal code in the world. There is a huge variety of them with different digits and letters. So it will be helpful for you.