Zip code validation

Text entry open-end questions can be customized to accept zip codes. Text entry questions should be utilized since some zip codes begin with 0, and leading zeros will not be saved in numeric questions. This script can be applied with text entry questions to ensure that only numbers forming a valid zip code can be entered in the text field.

addPostValidationHandler("Zip Code", () => {
  const respondentZipCode = getValue("Zip Code");
  const zipCodeRegex = /^\d{5}(?:[-\s]\d{4})?$/; //expression from https://stackoverflow.com/questions/2577236/regex-for-zip-code
 
  const zipCodeValid = zipCodeRegex.test(respondentZipCode);
 
  if(!zipCodeValid){
    return "Please enter a valid zip code.";
  }
});

When implemented, the error will appear like this:

An open-end question with a partially filled in zip code with an error saying "Please enter a valid zip code."