freewebwithme
freewebwithme

Reputation: 579

Validating form without onChange in React

I have a form.

export const UserInfoForm = (props) => {
  const [user] = props
  const [name, setName] = React.useState(user ? user.name : "");
  const [intro, setIntro] = React.useState(user ? user.intro: "");

   const [
    nameValidationState,
    setNameValidationState,
  ] = React.useState("");

  const [
    introValidationState,
    setIntroValidationState,
  ] = React.useState("");

  return (
    <form>
     <Input defaultValue={name} onChange={
      () => {
           if(validateForm()) {
             setNameValidatetionState("success");
           } else {
             setNameValidationState("false");
           }
           setName(e.targeto.value);
        }
      }
     />
     <Input defaultValue={intro} />
    </form>
  )

}

code is simplified. My problem happens when I update the user info. Because it is displayed with initial value. And sometimes I don't want to change other info but name. So leave the input field untouched.

But my validation logic happens in onChange function. Form isn't validated even if I don't type in field.

So how can I solve this problem?

Upvotes: 0

Views: 650

Answers (1)

Hadi Pawar
Hadi Pawar

Reputation: 1126

You could form validation at the very end i.e onSubmit. So say you fill all the fields and then press on submit, before submitting validate all the fields and highlight errors so users can correct them. You could also use a library called Formik that makes these kinds of validations pretty intuitive and easy.

Upvotes: 1

Related Questions