This snippet provides a custom React hook, useFormValidation, to handle form validation in a web application.
import { useState } from 'react'; export const useFormValidation = (initialState, validate) => { const [values, setValues] = useState(initialState); const [errors, setErrors] = useState({}); const handleChange = event => { const { name, value } = event.target; setValues({ ...values, [name]: value }); }; const handleSubmit = event => { event.preventDefault(); const validationErrors = validate(values); setErrors(validationErrors); if (Object.keys(validationErrors).length === 0) { // Submit the form } }; return { values, handleChange, handleSubmit, errors }; };
The useFormValidation hook simplifies form handling and validation in React applications by providing a reusable and customizable solution. It enhances user experience by ensuring data integrity and guiding users through the form submission process.
Disclaimer: This snippet is intended for educational purposes and may require additional customization to suit specific form requirements.