Home > Net >  How can I have a XNOR-like behaviour on required input?
How can I have a XNOR-like behaviour on required input?

Time:08-18

I have the following form:

<form>
        <input type="text" name="input1">
        <input type="text" name="input2">
        <button type="submit">submit</button>
    </form>

Using Bootstrap, I am trying to prevent the user from inputting only 1 field ; i.e. Not inputting anything is fine, inputting both fields is fine, inputting one field but not the other is not fine.
I read Validation but could not find a solution to my problem.
What is the best way to solve this issue ?

CodePudding user response:

You can compare the comparisons with an empty string to tell if they're both empty or both non-empty.

document.querySelector("form").addEventListener("submit", e => {
  let value1 = document.querySelector('[name=input1]').value;
  let value2 = document.querySelector('[name=input2]').value;
  if ((value1 == '') != (value2 == '')) {
    e.preventDefault();
    console.log('Fill in both inputs or neither');
  } else {
    e.preventDefault(); // just for snippet here
    console.log('Form was submitted');
  }
});
<form>
  <input type="text" name="input1">
  <input type="text" name="input2">
  <button type="submit">submit</button>
</form>

  • Related