Negar Nasiri
Negar Nasiri

Reputation: 466

Disable button until all form inputs are validated in React

I have this form in my code, I want to, after checking all validation and patterns, the form button to become enabled, but I don't know how I can put this in my form, or do I need to write any other functions and which way is most clean Code?

const [disable, setDisable] = React.useState(true);

  const [staff, setStaff] = React.useState({
    username: "",
    email: "",
    phone: "",
    password: "",
  });

  const [errMessage, setErrMessage] = React.useState({
    username: "",
    email: "",
    phone: "",
    password: "",
  });

const handleChange = (e) => {
    switch (e.target.name) {
      case "email": {
        if (e.target.value.toLowerCase().match(emailValidation)) {
          setErrMessage({ ...errMessage, email: "" });
          setStaff({ ...staff, email: e.target.value });
        } else {
          setErrMessage({
            ...errMessage,
            email: "It should be a valid email address",
          });
        }
      }
      case "password": {
        if (e.target.value.length >= 12) {
          setErrMessage({ ...errMessage, password: "" });
          setStaff({ ...staff, password: e.target.value });
        } else {
          setErrMessage({
            ...errMessage,
            password: "It should be at least 12 character",
          });
        }
      }
      default:
        setStaff({
          ...staff,
          [e.target.name]: e.target.value,
        });
    }
  };

return( <button disabled={disable}>Submit</button>)

Upvotes: 1

Views: 74

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 46221

Since you are tracking the errors in that errMessage state, you don't need an additional state for disable. It could be a simple constant you can add above and outside handleChange:

const disable =
  Object.values(errMessage).filter((v) => v).length > 0 ||
  Object.values(staff).filter((v) => v).length !== 4;
<button disabled={disable}>Submit</button>

This way, the button is disabled when there is an error message, or when one field is empty.

Upvotes: 1

Related Questions