custom hooks for password input code example
Example: 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 ]
}