Back to snippets

Form Validation Hook

Snippet Overview

This snippet provides a custom React hook, useFormValidation, to handle form validation in a web application.

Code

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 }; };

Usage

  • Import and use the useFormValidation hook within your React components.
  • Pass initial form values and a validation function to the hook.
  • Use the returned values, functions, and errors to manage form state and perform validation.

Conclusion

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.