How to stop submit if checkbox is not checked

Viewed 25

I'm trying to stop the process of registration if the checkbox is not marked! Already did the configuration but failed to stop the process if the checkbox is not marked, now the code is only showing an error when I click on the box and then click again here it shown an error "You must accept the terms" but i want it to show error if the user didn't checked the box, in other words stop the handlesubmit process.

Register.jsx:

export default function Register() {

  const [error, setError] = useState(false);
  const [checked, setChecked] = useState(true);
  const [errorCheckbox, setErrorCheckbox] = useState(null);

  const handleCheckBoxChange = (event) => {
    if (event.target.checked) {
        setChecked(true);
        setErrorCheckbox(null);
        console.log("ACCEPTED TERMS");
    } else {
      setChecked(false);
      console.log("DIDN'T ACCEPT TERMS");
      setErrorCheckbox("You must accept the terms");
    }
  };

  const handleSubmit = async (e) => {
    if (checked === false) {
      setError(true);
      setErrorCheckbox("You must accept the terms");
    } else {
      e.preventDefault();
    dispatch({ type: "REGISTER_START" });
    try {
      const res = await axios.post("/register", regCredentials);
      dispatch({ type: "REGISTER_SUCCESS", payload: res.data.user });
      navigate("/");
    } catch (err) {
      dispatch({ type: "REGISTER_FAILURE" });
      setMsg({ fail: true, msg: err.response.data.message });
      setError(true);
    }
  }
  };

  return (
    <div className="register">
            <Box>
              <Stack>
                  <Box>
                        <Stack>
                              
                          {/* REGISTER FORM */}
                          <form onSubmit={handleSubmit}>
                            <Stack>
                                {/* CHECKBOX */}
                                <Box >
                                  <FormGroup>
                                  <FormControlLabel 
                                  control={errorCheckbox ? (<Checkbox onChange={handleCheckBoxChange} sx={{
                                    color: red[600] ,
                                    '&.Mui-checked': {
                                      color: "black",
                                    },
                                  }}/>
                                  ) : (
                                    <Checkbox onChange={handleCheckBoxChange} />
                                  )} 
                                  label={<Typography> </Typography>}
                                  />
                                </FormGroup>
                                </Box>
                                {/* ENDS OF CHECKBOX */}

                           {/* SUBMIT BUTTON */}
                            <button>
                              className="registerButton"
                              type="submit"
                              disabled={isFetching}>
                              </button>
                              {/* ENDS OF SUBMIT BUTTON */}
                            </Stack>
                          </form>
                          
                          {/* TO SHOW ERROR IF THE CEHECK BOX IS NOT CHECKED */}
                            {errorCheckbox && 
                            <Typography
                              style={{ color: "red", textAlign: "center" }}
                              mt={2}>
                              {errorCheckbox}
                            </Typography> }
                            {/* ENDS OF TO SHOW ERROR IF THE CEHECK BOX IS NOT CHECKED */}

                          {/* ENDS OF REGISTER FORM */}

                        </Stack>
                  </Box>
                </Stack>
        </Box>
    </div>
  )}

I failed to stop the process with the code above, any help would be appreciated.

1 Answers

Just bring your preventDefault call to the top.

In your old code, you have prevented the submit event when the user has checked the box.

Just bring to top, so that even when the user is not checked the box, let's not submit the form.

const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (checked === false) {
        setError(true);
        setErrorCheckbox("You must accept the terms");
    } else {
        dispatch({ type: "REGISTER_START" });
        try {
            const res = await axios.post("/register", regCredentials);
            dispatch({ type: "REGISTER_SUCCESS", payload: res.data.user });
            navigate("/");
        } catch (err) {
            dispatch({ type: "REGISTER_FAILURE" });
            setMsg({ fail: true, msg: err.response.data.message });
            setError(true);
        }
    }
};
Related