Home > other >  How can validation form before submitting in react js?
How can validation form before submitting in react js?

Time:10-19

How can validation Login form before submitting And make button disable until all form is valid in react js ( function component ) ?

CodePudding user response:

I think to react hook form can help in solving form problems. Link

CodePudding user response:

You can validate the form by using the library or using useEffect.

My suggested library is React Hook Form. You can get it here - https://react-hook-form.com/

Also you can use Yup for validation - https://github.com/jquense/yup

By useEffect method:

const [name, setName] = useState('')
const [email, setEmail] = useState('');

useEffect(() => {

 // Run your validation function
  
 // if all the data are valid, then enable the form
  
}, [name, email]) // Only re-run the effect if name or email change


// When the form submit button is clicked
function onHandleSubmit(){
  // check the name is empty or not
  // check if email is not empty and valid or not
  
  //if all form fields are valid, submit form value;
  submitForm(values);
}

  • Related