React has gained immense popularity due to its component-based architecture and reusability. One common scenario in web applications involves managing forms and handling their validation effectively. In this blog post, we will create a custom hook in React specifically designed for form validation, allowing us to manage form state and validation logic cleanly.
Custom hooks allow developers to encapsulate logic that can be reused across multiple components. When it comes to forms, validating user input can become complicated, especially when the forms contain multiple fields with varying validation rules. By creating a custom hook, we can ensure that our validation logic is consistent and maintainable.
Let’s build a custom hook called useFormValidation
that will handle form state and validation.
Start by creating a new file named useFormValidation.js
in your project directory.
// useFormValidation.js import { useState } from 'react'; const useFormValidation = (initialState, validate) => { const [values, setValues] = useState(initialState); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const handleChange = (event) => { const { name, value } = event.target; setValues({ ...values, [name]: value }); }; const handleSubmit = (event) => { event.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; return { handleChange, handleSubmit, values, errors, isSubmitting }; }; export default useFormValidation;
The custom hook takes two arguments: initialState
(which will hold the initial state of the form fields) and validate
(a validation function that checks if the input values are valid).
Here’s an example validation function:
// validate.js const validate = (values) => { let errors = {}; if (!values.email) { errors.email = 'Email is required'; } else if (!/\S+@\S+\.\S+/.test(values.email)) { errors.email = 'Email address is invalid'; } if (!values.password) { errors.password = 'Password is required'; } else if (values.password.length < 6) { errors.password = 'Password must be at least 6 characters'; } return errors; }; export default validate;
Now, let’s create a React component that uses our useFormValidation
hook along with the validation logic.
// SignupForm.js import React from 'react'; import useFormValidation from './useFormValidation'; import validate from './validate'; const SignupForm = () => { const initialState = { email: '', password: '' }; const { handleChange, handleSubmit, values, errors, isSubmitting } = useFormValidation(initialState, validate); return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="email">Email:</label> <input type="email" name="email" value={values.email} onChange={handleChange} /> {errors.email && <p>{errors.email}</p>} </div> <div> <label htmlFor="password">Password:</label> <input type="password" name="password" value={values.password} onChange={handleChange} /> {errors.password && <p>{errors.password}</p>} </div> <button type="submit" disabled={isSubmitting}>Sign Up</button> </form> ); }; export default SignupForm;
State Initialization: We initialize the state for email and password using our initialState
.
Handle Change: The handleChange
function is attached to the input fields to update the form state dynamically.
Error Messages: If any validation errors occur, they will be displayed below each corresponding input field.
Form Submission: The handleSubmit
function validates the form before proceeding. If there are no errors detected, you can proceed with further actions, such as making an API call.
You can now import the SignupForm
component into your main App component and render it. Try inputting various scenarios, such as invalid email formats and short passwords, and you should see relevant error messages.
This custom hook provides a flexible way to handle forms in React applications, and you can easily extend it to accommodate different input types or to include additional validation rules.
Feel free to tweak the validation logic to meet your specific application needs, making the hook as straightforward or complex as necessary. Happy coding!
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS