Password Validation Schema

Password validation using the yup library

Code Snippet

password-validator.ts
import * as yup from 'yup';

export const validationSchema = yup.object({
  password: yup
    .string()
    .matches(/^(?=.{8,36}$)/, 'The password length must be between 8-36 characters')
    .matches(/^(?=.*[a-z])/, 'The password must contain at least one lower case letter')
    .matches(/^(?=.*[A-Z])/, 'The password must contain at least one upper case letter')
    .matches(/^(?=.*[0-9])/, 'The password must contain at least one number')
    .matches(/^(?=.*[!@#%&])/, 'The password must contain at least one special character')
    .required('This field is required.')
    .trim(),
  confirmPassword: yup
    .string()
    .required('This field is required')
    .oneOf([yup.ref('password'), null], 'Passwords do not match.')
    .trim(),
});

Shorter Version

password-validator.ts
import * as yup from 'yup';

export const validationSchema = yup.object({
  password: yup
    .string()
    .required('This field is required.')
    .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,36}$)/, 'Must follow the password rules')
    .trim(),
  confirmPassword: yup
    .string()
    .required('This field is required')
    .oneOf([yup.ref('password'), null], 'Passwords do not match.')
    .trim(),
});

Usage

This is an example usage with React Hook Form (RHF).

  1. Install the dependencies
  npm install react-hook-form @hookform/resolvers yup
  1. Pass a resolver to RHF's useForm
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { validationSchema } from './password-validator.ts';

type Fields = {
  password: string;
  confirmPassword: string;
};

function App() {
  const myForm = useForm<Fields>({
    mode: 'onSubmit',
    resolver: yupResolver(validationSchema),
    defaultValues: {
      password: '',
      confirmPassword: '',
    },
  });

  // render here
}

And that's it! If you want to know the fundamentals of RHF, you may refer to my post here.