DEV Community

Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

1 1

How to make a password validation with Regex or Yup

Password Validation with Regex


const isUpperCase = new RegExp(/(?=.*[A-Z])/g)
const isSpecialChar = new RegExp(/(?=./*[!@#$%^&*])/g)
const isLowerCase = new RegExp(/(?=./*[a-z])/g)
const isLong = new RegExp(/(?=.{7,})/g)
const checkIsWhiteSpacefromBegAndEnd = new RegExp(/^[^][\w\W]*[^]/g)

const passwordValidation = (currentPassword: string): boolean => {
 if(
   currentPassword.match(isUpperCase) &&
   currentPassword.match(isSpecialChar) &&
   currentPassword.match(isLowerCase) &&
   currentPassword.match(isLong) && 
   currentPassword.match(checkIsWhiteSpacefromBegAndEnd) 
 ) {
   return true
 }
 return false
}

Enter fullscreen mode Exit fullscreen mode

For the tests I am using Jest and taking a TDD approach.

You can write lots of tests these are just a few of the samples I wrote.

describe('Given the pssword validation function', () => {
 test('test passing requirements', () => {
  expect(passwordValidation('Aa!1uj8h')).toBe(true)
  expect(passwordValidation('1_c_A_!2')).toBe(true)
  expect(passwordValidation('A b 1 ! 2 %')).toBe(true)
  expect(passwordValidation('_13Bbhjj@}}j>_')).toBe(true)
})

test('test failing password requirements', () => {
 expect(passwordValidation(' ahhhhh')).toBe(false)
 expect(passwordValidation(' aAhhhhh')).toBe(false)
 expect(passwordValidation(' aA122hhhhh')).toBe(false)
 expect(passwordValidation(' 111111122')).toBe(false)
 expect(passwordValidation(' 111111122aA')).toBe(false)
 expect(passwordValidation(' Bba !')).toBe(false)
 })
})
Enter fullscreen mode Exit fullscreen mode

Password Validation with Yup

Yup Link


export const passwordValidation = Yup.string()
  .trim()
  .required('Required')
  .matches(
    /(?=.*[A-Z])/,
    'Your password needs to have at least one capital letter',
  )
  .matches(
    /(?=.*[!@#$%^&*])/,
    'Your password needs to have at least one special character',
  )
  .matches(
    /(?=.*[a-z])/,
    'Your password needs to have at least one lower case character',
  )
  .matches(/(?=.*[0-9])/, 'Your password needs to have at least one number')
  .min(8)
  .max(200)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay