Validating Postal Code / ZipCode without Regular Expressions in React JS

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.

ยท

2 min read

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...

Screenshot 2022-05-04 at 4.03.53 PM.png

๐Ÿ“š 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 ๐Ÿ˜…

Screenshot 2022-05-04 at 5.14.33 PM.png

ย