bk___
bk___

Reputation: 71

Validating a zipcode input with javascript

I am working on an input component that takes the zipcode input and allows numbers only with a max length of 5 characters. I have that working fine, but now I am also trying to validate that zip code as well. I am using the following pieces of code:

  const onChangeInput = (fieldName, e) => {
    setValidate(false);

    const newHomeAddress = homeAddress;

    newHomeAddress[fieldName] = e.target.value;
    if (fieldName === "phone")
      newHomeAddress[fieldName] = e.target.value.replace(/\D/g, "");
    if (fieldName === "zipCode")
      newHomeAddress[fieldName] = e.target.value.replace(/\D/g, "");

    setHomeAddress({
      ...newHomeAddress,
    });
  };

  const isValidUSZip = (n) => {
    return /^\d{5}(-\d{4})?$/.test(n);
  };

and...

<div className="form-field">
  <Input
    label="Zip code"
    placeholder="Zip code"
    onChange={(e) => onChangeInput("zipCode", e)}
    value={homeAddress.zipCode}
    error={validate && homeAddress.zipCode === ""}
    errorLabel="Zip code is not valid"
    maxlength="5"
  />
</div>

I am trying to figure out how i can make sure that fieldName "zipCode" validates through isValidUSZip as well. Any input would be appreciated.

Upvotes: 1

Views: 2313

Answers (2)

Memorabilien
Memorabilien

Reputation: 1

I faced the same problem. But not every 5 digit number is also a zip code. Therefore I made/generated a really long regular expression. Although long, the actual storage space they take up is quite small and it's impressively fast.

This although it is county specific and as of now I only made these countries: US, CH, AT and Germany. If you need another country please let me know.

You can find all of them in this Repository

Upvotes: 0

user2560539
user2560539

Reputation:

Try to see if you could add something like this in your <Input element.

<div className="form-field">
  <Input
    label="Zip code"
    placeholder="Zip code"
    onChange={(e) => onChangeInput("zipCode", e)}
    value={homeAddress.zipCode}
    error={validate && homeAddress.zipCode === ""}
    errorLabel="Zip code is not valid"
    pattern="[\d]{3}" // accept only 3-digit numbers in this example
    maxlength="5"
  />
</div>

Upvotes: 1

Related Questions