Skip to content

Instantly share code, notes, and snippets.

@jokklan
Last active December 17, 2020 11:31
Show Gist options
  • Save jokklan/6b405ff3ae3d19b369c768e1bd1491f4 to your computer and use it in GitHub Desktop.
Save jokklan/6b405ff3ae3d19b369c768e1bd1491f4 to your computer and use it in GitHub Desktop.
// Async example (returns a promise)
// Use case: you need a function to validate values after specific events (i.e. onSubmit)
const useFormValidation = (schema, values) => async () => {
try {
const isValidated = await schema.validate(values, {
abortEarly: false
})
return isValidated
} catch (error) {
const { errors } = error
return { errors }
}
}
// Sync example (returns a boolean and a error object)
// Use case: you need to automatically validate form values as they change
const useFormValidation = (schema, values) => {
const [isValid, setIsValid] = useState()
const [errors, setErrors] = useState()
useEffect(() => {
const validateValues = async () => {
try {
const isValidated = await schema.validate(values, {
abortEarly: false
})
setIsValid(true)
setErrors()
} catch (error) {
const { errors } = error
setErrors(errors)
setIsValid(false)
}
}
validateValues()
}, [values])
return [isValid, isValid ? undefined : errors]
}
// Combined example (returns both a boolean and a error object, as well as a async function for validating)
// Use case: you need to automatically validate form values as they change, as well as after specific events (i.e. onSubmit)
const useFormValidation = (schema, values) => {
const [isValid, setIsValid] = useState()
const [errors, setErrors] = useState()
const validateValues = useCallback(
async () => {
try {
const isValidated = await schema.validate(values, {
abortEarly: false
})
setIsValid(true)
setErrors()
} catch (error) {
const { errors } = error
setErrors(errors)
setIsValid(false)
}
},
[values]
)
useEffect(() => {
validateValues()
}, [validateValues])
return [isValid, isValid ? undefined : errors, validateValues]
}
export default useFormValidation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment