validation password react hooks code example

Example 1: how to validate password and confirm password on react form hook

const validationSchema = yup.object().shape({
    newPassword: yup.string()
      .required('New Password is required'),
    confirmPassword: yup.string()
      .required('Confirm Password is required')
      .oneOf([yup.ref('password'), null], 'Passwords does not match'),
  });

Example 2: custom hooks for password input

function useForm(initialValues, validateForm) {
  if (!initialValues) {
    throw Error('Initial values are required')
  }

  const values = {}
  const valuesWithSetters = {}
  const [errors, setErrors ] = useState({})
  const keys =  Object.keys(initialValues)

  for (let i = 0, l = keys.length; i < l; i ++) {
    const key = keys[i]
    const [val, setVal] = useInputValue(initialValues[key])
    const setValWrapper = (...pars) => {
      if (errors[key]) {
        const er = {...errors}
        delete er[key]
        setErrors(er)
      }
      setVal(...pars)
    }
    valuesWithSetters[key] = [val, setValWrapper, () => errors[key]]
    values[key] = val
  }

  function validate() {
    const errorObject = {}
    validateForm(errorObject, values)
    setErrors(errorObject)
    return Object.keys(errorObject).length < 1
  }

  return  [valuesWithSetters, validate, errors, values ]
}