Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show error if client did not click check, but with not default value

I am trying to show error message if client did not click checkbox, but it shows the error message by default.
How do I manage to show it only after submission?

const InputForm=()=>{
    const [value ,setValue] = useState("");
    const [check,setCheck] = useState(null)

    const getValue=(e)=>{
        setValue(e.target.value);
    }

    const getCheck=(e)=>{
        setCheck(e.target.checked);
    }

    const handleSubmit=(e)=>{
        e.preventDefault();
        const emailValidator =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
        if (value.match(emailValidator)) {
            console.log("Valid");
        }else{
            console.log("Invalid");
        }
        
    };

    return(
        <form className="inputForm" onSubmit={handleSubmit}>
            <div className="tos" >
                <label className="container">
                    <span>I agree to <strong>terms of service</strong></span>
                    <input type="checkbox" onChange={getCheck}/>
                    <span className="checkmark" ></span>
                </label>
                <p style={check?{display:"none"}:{display:"block",color:"red"}}>You must accept the terms and conditions</p>
            </div>
            <Footer/>
        </form>
    )
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { useEffect, useState } from "react";

export default function App() {
  const [checked, setChecked] = useState(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    checked && setError(false);
  }, [checked, setError]);

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!checked) {
      setError(true);
    } else {
      // do what you want
    }
  };

  return (
    <form className="inputForm" onSubmit={handleSubmit}>
      <div className="tos">
        <label className="container">
          <span>
            I agree to <strong>terms of service</strong>
          </span>
          <input
            type="checkbox"
            onChange={(e) => setChecked(e.target.checked)}
          />
          <span className="checkmark"></span>
        </label>
        {error && (
          <p style={{ color: "red" }}>
            You must accept the terms and conditions
          </p>
        )}
      </div>

      <button type="submit">submit</button>
    </form>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Here is a solution :
https://codesandbox.io/s/crimson-field-m6j5h?file=/src/App.js

You should have a separate state for the error and render the message only if that state is truthy.
That state should be set when calling you handleSubmit function.
To remove the error message when the checkbox is checked, you can listen to it in a useEffect hook.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading