Created
October 25, 2021 15:39
-
-
Save devmnj/73cad8f699f2a0e911c59af40a473f4c to your computer and use it in GitHub Desktop.
React Custom Hook for data validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function SignUp() { | |
const { errors, values, handleChange, handleSubmit } = useForm(() => { | |
console.log('No errors found') | |
console.log('Can implement mutation here') | |
}, Validate) | |
return ( | |
<form ...>) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EventRounded } from '@mui/icons-material'; | |
import { useState, useEffect } from 'react'; | |
const useForm = (callback, validate) => { | |
const [values, setValues] = useState({}); | |
const [errors, setErrors] = useState({}); | |
const [isSubmitting, setIsSubmitting] = useState(false); | |
useEffect(() => { | |
if (Object.keys(errors).length === 0 && isSubmitting) { | |
callback(); | |
} | |
}, [errors]); | |
const handleSubmit = (event) => { | |
if (event) event.preventDefault(); | |
setErrors(validate(values)); | |
setIsSubmitting(true); | |
event.target.reset(); | |
}; | |
const handleChange = (event) => { | |
// event.persist(); | |
setValues(values => ({ ...values, [event.target.name]: event.target.value, [event.target.email]: event.target.value })); | |
}; | |
return { | |
handleChange, | |
handleSubmit, | |
values, | |
errors, | |
} | |
}; | |
export default useForm; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function Validate(values) { | |
let errors = {}; | |
if (!values.email) { | |
errors.email = 'Email address is required'; | |
} else if (!/\S+@\S+\.\S+/.test(values.email)) { | |
errors.email = 'Email address is invalid'; | |
} | |
if (!values.name) { | |
errors.name = 'Name is required'; | |
} else if (values.name.length < 3) { | |
errors.name = 'Name must be 3 or more characters'; | |
} | |
if (!values.password) { | |
errors.password = 'Password is required'; | |
} else if (values.password.length < 8) { | |
errors.password = 'Password must be 8 or more characters'; | |
} | |
return errors; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment