Reputation: 133
Need to write Proper Regex that will maximum 9 digits and regex will match "02142-1209", but if anyone is mentioning 5 digits also then we can allow user to submit. Maximum 9digits, and it should have "-" included within it.
Note- User can able to submit if he added first 5 digits.
if ( !props.postalCode )
{
err.postalCode = "Zip Code is Required.";
} else if ( props.countryCode === "US" && !/^[\d]+\-*[\d]\{9}$/.test( props.postalCode ) )
{
err.postalCode = "US Zip Codes Must Be 5 Digits";
}
Upvotes: 1
Views: 59
Reputation: 2332
This should match 5 digits, and optionally 4 more digits. The hyphen in between is optional.
/^[0-9]{5}-?([0-9]{4})?$/
I've used this library which also handles international postal codes: https://github.com/Cimpress-MCP/postal-codes-js/
Upvotes: 4