Is there a way to show warning for multiple required inputs that are left empty simultaneously?

50 Views Asked by At

In JavaScript (used in React), while using inputs, I used the "required" prop in some inputs in a form. However, when multiple fields are left empty, the warning only shows up in the first required input that was left empty.

3 sample inputs with required prop

The code for the same:

<form method="post" name="Form" onsubmit="" action="">
    <input length="20" required=""></input>
    <input length="20" required=""></input>
    <input length="20" required=""></input>
    <input type="submit" value="Submit"></input>
</form>

I tried to change the required prop to manually handling the empty inputs but when the forms are really long, it's not practical. Is there a way I can show the same warning for every field that is left empty?

Thanks

1

There are 1 best solutions below

0
SmartFellah On

If you are using React, you may use useState hook to store input value of your inputs and render warnings for each empty input.

For example:

  const [inputA, setInputA] = useState('');
  const [inputB, setInputB] = useState('');
  const [inputC, setInputC] = useState('');

  const handleAChange = (event) => {
    setInputA(event.target.value);
  };

  const handleBChange = (event) => {
    setInputB(event.target.value);
  };

  const handleCChange = (event) => {
    setInputC(event.target.value);
  };

  return (
    <form>
      <label>
        Input A:
        <input type="text" value={inputA} onChange={handleAChange} />
      </label>
      <p>Input A: {inputA}</p>
      {!inputA && <p>Cannot be empty!</p>}
      <label>
        Input B:
        <input type="text" value={inputB} onChange={handleBChange} />
      </label>
      <p>Input B: {inputB}</p>
      {!inputB && <p>Cannot be empty!</p>}
      <label>
        Input C:
        <input type="text" value={inputC} onChange={handleCChange} />
      </label>
      <p>Input C: {inputC}</p>
      {!inputC && <p>Cannot be empty!</p>}
    </form>
  );

This code will display a warning for each empty input. You could also use absolute positioning and z-index in css to make these warning look more like what you had whith required attribute.

You may aslo keep required attribute for accessibility though.