Instead of coding up lots of code to check whether the input is valid, you can simply create a custom hook that does all this stuff for you by encapsulating all the validation logic.
Let’s create a custom hook for form validation :
Define the hook :
import {useState } from 'react'; function useFormValidation(initialValues , validationSchema){ // }
This hook takes 2 arguments : initialValues (the initial values for the form fields) and validationSchema ( a schema that defines the validation rules for each field).
Manage form state :
const [values , setValues] = useState(initialValues);
const [errors , setErrors] = useState({});
const [isSubmitting , setIsSubmitting ] = useState(false);
This code creates three state variables : values , errors , isSubmitting
Handle input changes :
const handleChange = (event) => {
const {name , value } = event.target;
setValues({...values , [name] : value});
};
This function updates the values state when the user types something into a form field.<!-- notionvc: db6c9ea1-3409-4ebe-90bb-8fb92cf47469 -->
Validate the form :<!-- notionvc: ad248313-bafe-4a77-8df6-6692016d2611 -->
const handleSubmit = async (event) => {
event.preventDefault();
setIsSubmitting(true);
try {
await validateSchema.validate(values , { abortEarly: false });
}catch (errors) {
setErrors(errors.inner.reduce((acc , error ) => ({...acc , [error.path]:error.message }), {}));
} finally {
setIsSubmitting(false);
}
};
This function handles form submission.<!-- notionvc: 2c082e47-b8a8-4769-a1ff-93b15cd877b2 -->
Return the hook :<!-- notionvc: 250dfd5a-090e-43b4-85e1-9a1410aa637e -->
return {
values ,
errors,
isSubmitting,
handleChange ,
handleSubmit,
};
This returns an object that can be used in your component to access the form values , errors , and submission status.
<!-- notionvc: 287c4c61-b01f-4e91-9e8c-f9613bef755a -->Now you can use this custom hook in your form component :
<!-- notionvc: 346bf29a-439f-4201-ac02-b81101c0e1a7 -->
import {useFromValidation } from './From';
function MyForm(){
const {values , errors , isSubmitting , handleChange , handleSubmit } = useFormValidation(
{ name: '' , email: '' },
);
return (
<form onSubmit = {handleSubmit}>
{ /* ...... form fields */ }
<button type = " submit " disabled= {isSubmitting}>Submit</button>
</form>
);
}<!-- notionvc: 7899c47b-e764-451e-9657-e39bac4a50ee -->