Validating Postal Code / ZipCode without Regular Expressions in React JS
I used to use regular expressions but now I prefer open-source libraries to save valuable time and to avoid bugs.
I don't like writing regexp for validations because of the absence of readability for team members. Usually, team members don't force themself to understand regexp but they ask the author of that logic ๐.
A wise person said "Always prefer open source libraries over your own logic if you are allowed" because multiple brains contribute to it and multiple brains can perform better than a single brain. ๐
So I found a beautiful library that provides us the synthetic sugar but it uses regexp in the engine, who cares...
๐ Overview
import { postcodeValidator, postcodeValidatorExistsForCountry } from 'postcode-validator';
postcodeValidator('20521-9000', 'US'); // returns true โ
postcodeValidator('123456722', 'US'); // returns false โ
๐ป Implementation
Let's create a practice app and implement this logic, right now, we are not going to practice using the input field but just a simple message printing on a webpage.
๐ 1. Install Package
Doesn't matter if you are using npm
or yarn
npm i postcode-validator
โ๏ธ 2. Create Custom Hook
It will accept 2 params and will update the state with the help of useEffect
when both parameters change
// src/usePostcodeValidator.ts
import { useEffect, useState } from 'react';
import { postcodeValidator } from 'postcode-validator';
const usePostcodeValidator = (postCode: string, country: string) => {
const [isValid, setIsValid] = useState(true);
useEffect(() => {
const validate = postcodeValidator(postCode, country);
setIsValid(validate);
}, [postCode, country]);
return {
isValid
}
}
export default usePostcodeValidator
โ๏ธ 3. Add Custom Hook into App
Not used input field for checking but just a simple printing on a webpage.
// src/App.tsx
import usePostcodeValidator from './usePostcodeValidator';
function App() {
const { isValid } = usePostcodeValidator("20521-9000", "US");
return (
<div>{isValid ? "This is valid" : "This is not valid"}</div>
);
}
export default App;
๐ 4. Results
Output is This is valid
because I entered the correct format but if I type the wrong format it will be invalid, I swear ๐