-1

I was working on simple form Validation, when I press login button. It should check all the required field whether they are empty or not ? if yes then show the error message.

Below is the code snippet.

  const [user, setUser] = useState({
    name: "",
    password: "",
    email: "",
    confirmpassword: "",
  });
  const [formErrors, setFormErrors] = useState({
    name: "",
    password: "",
    email: "",
    confirmpassword: "",
  });


onSubmit:
  const handleSubmit = (e) => {
    e.preventDefault();
    const isFormValid = validForm();
    
  };


  const validForm = () => {
    if (
      user.email.trim() === "" ||
      user.password.trim() === "" ||
      user.name.trim() === ""
    ) {
      if (user.password.trim() === "") {
        setFormErrors({
          ...formErrors,
          password: "Password Length must be between 4 and 6 characters",
        });
        
      }

      if (user.name.trim() === "") {
        setFormErrors({ ...formErrors, name: "Required Field" });
        
      }
      if (user.email.trim() === "") {
        setFormErrors({ ...formErrors, email: "Required Field" });
       
      }

      return false;
    } else {
      setFormErrors({ ...formErrors, email: "", password: "", name: "" });
      return true;
    }
  };
 {formErrors.email === "" ? null : (
          <div className="">{formErrors.email}</div>
        )}

Only email field is showing the required filled error, all are not getting updated.

Below is the snapshot of user object after clicking on login button.

{name: '', password: '', email: 'Required Field', confirmpassword: ''}

Please help on this.

3 Answers3

2

It is not working because you are trying to setState values same time, before updating so on the last line (email check) it will update the state with old values since none of the above setState is completed

I have a different method of implementation for validForm function

const validForm = () => {
    let valid = true;
    let tempFormErros = {}
      if (user.password.trim() === "") { //&& add password condition check
          tempFormErros.password = "Password Length must be between 4 and ...";
          valid = false;
      }

      if (user.name.trim() === "") {
          tempFormErros.name = "Required Field";
          valid = false;
      }
      if (user.email.trim() === "") {
        tempFormErros.email =  "Required Field";
        valid = false;
      }
      if(!valid) {
          setFormErrors(tempFormErros)
      }
      return valid;
    }
  };
sojin
  • 2,158
  • 1
  • 10
  • 18
2

Because when the state change in name and password if clause. It ain't reflect change in email if clause try to save it in local variable for eg


const validForm=()=>{
let errorObj={}
if (user.name.trim() === "") {
        errorObj.name= "Required Field"       
      }

....
setFormErrors({...formErrors,...errorObj})

}

MhkAsif
  • 537
  • 3
  • 18
1

setState doesnt mutate the state it repalces it with a new object and this is asynchronous function . you have to update it with the function way

setFormErrors((formErrors)=>({ ...formErrors,  password: "Password Length must be between 4 and 6 characters"}));
setFormErrors((formErrors)=>({ ...formErrors, name: "Required Field" }));
setFormErrors((formErrors)=>({ ...formErrors, email: "Required Field" }));

Check out react docs for more info hooks state react docs

karthik rao
  • 121
  • 5
  • This is another method to set state values. but this is not a solution for his problem – sojin Dec 14 '21 at 15:54
  • if he simultaneously update the states only the last one will work. because third setState uses the same old `formErrors` the first and second update will not affect here because third one using form errors before the updation – sojin Dec 14 '21 at 15:55