1

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>)
4
  • Hi Negar! I pasted an answer; please check it and let me know! Commented Jan 2, 2023 at 17:58
  • Hi. at the very first level all my errMessage state are empty strings and like when we have no error and the button at very first level is enable because errMessage length all is zero. Commented Jan 3, 2023 at 7:15
  • I see Negar! Check my updated answer please, and let me know. Commented Jan 13, 2023 at 11:23
  • Handling form validations in react with bare javascript code is difficult . I recommend you using libraries like Formik or react hook form . Commented Mar 9, 2023 at 17:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.