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.
HTMLinput typenumber? In case you can't why don't you use anHTMLinput type text with regular expression validation.onChangeInput()function needs to callisValidUSZip(e.target.value)and use the result to indicate whether the field is valid, probably by settingvalidateto false.<Input>element can you add this attributepattern?