Skip to content

Instantly share code, notes, and snippets.

@ali-sabry
Created March 27, 2023 14:03
Show Gist options
  • Save ali-sabry/712adaf406f2bd14dd92493027e426dd to your computer and use it in GitHub Desktop.
Save ali-sabry/712adaf406f2bd14dd92493027e426dd to your computer and use it in GitHub Desktop.
This custom hook allows you to easily handle form validation in your React application. It takes in an initial state and a validation function as parameters and returns an object with several properties and functions that can be used to manage the form state.
import { useState, useEffect } from 'react';
const useFormValidation = (initialState, validate) => {
const [values, setValues] = useState(initialState);
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
if (isSubmitting) {
const noErrors = Object.keys(errors).length === 0;
if (noErrors) {
console.log('authenticated', values);
setIsSubmitting(false);
} else {
setIsSubmitting(false);
}
}
}, [errors]);
const handleChange = event => {
setValues({
...values,
[event.target.name]: event.target.value
});
};
const handleBlur = () => {
const validationErrors = validate(values);
setErrors(validationErrors);
};
const handleSubmit = event => {
event.preventDefault();
const validationErrors = validate(values);
setErrors(validationErrors);
setIsSubmitting(true);
};
return { handleChange, handleSubmit, handleBlur, values, errors, isSubmitting };
};
//======== How to use in your react app ====================//.
import useFormValidation from './useFormValidation';
const INITIAL_STATE = {
email: '',
password: ''
};
const validateLogin = values => {
let errors = {};
// Validate email
if (!values.email) {
errors.email = 'Email is required';
} else if (!/\S+@\S+\.\S+/.test(values.email)) {
errors.email = 'Email is invalid';
}
// Validate password
if (!values.password) {
errors.password = 'Password is required';
} else if (values.password.length < 6) {
errors.password = 'Password must be at least six characters';
}
return errors;
};
const App = () => {
const { handleChange, handleSubmit, handleBlur, values, errors, isSubmitting } = useFormValidation(INITIAL_STATE, validateLogin);
return (
<form onSubmit={handleSubmit}>
<input type="email" name="email" placeholder="Email" value={values.email} onChange={handleChange} onBlur={handleBlur} />
{errors.email && <p>{errors.email}</p>}
<input type="password" name="password" placeholder="Password" value={values.password} onChange={handleChange} onBlur={handleBlur} />
{errors.password && <p>{errors.password}</p>}
<button type="submit" disabled={isSubmitting}>Submit</button>
</form>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment