JavaScript: Check whether a given value is US zip code or not
JavaScript validation with regular expression: Exercise-12 with Solution
Validate US Zip Code
Write a JavaScript function to check whether a given value is a US zip code or not.
Sample Solution:
JavaScript Code:
function is_usZipCode(str)
{
 regexp = /^[0-9]{5}(?:-[0-9]{4})?$/;
  
        if (regexp.test(str))
          {
            return true;
          }
        else
          {
            return false;
          }
}
console.log(is_usZipCode("03201-2150"));
console.log(is_usZipCode("7892"));
Output:
true false
Flowchart:

Live Demo:
See the Pen javascript-regexp-exercise-12 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript function that uses a regular expression to check if a string is a valid 5-digit or 9-digit US zip code.
 - Write a JavaScript function that validates a US zip code and returns a formatted version (e.g., 12345 or 12345-6789).
 - Write a JavaScript function that accepts a string and tests it against both 5-digit and ZIP+4 patterns.
 - Write a JavaScript function that handles non-numeric inputs by returning an error if the input is not a valid zip code.
 
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to check whether a given value is time string or not.
  Next: Write a JavaScript function to check whether a given value is UK Post Code or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
