首页 > 解决方案 > Javascript form validation: custom error message

问题描述

https://codepen.io/durja/pen/BPmmyR

I am trying to implement custom error messages for a form using the constraint api in html. Below is my code and I am facing an issue where after entering a wrong input and correcting it again, the validation message is still showing up. I am not sure what I am missing. I even tried to check the validity using checkValidity() method which is returning false even though the input is of the correct pattern.

const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input',e => {
    console.log(e.target.value);
   if(fp.validity.rangeOverflow) {
       fp.setCustomValidity('Custom message: greater than 100 not allowed.');
   }
});

ide.addEventListener('input',e => {
  console.log(e.target.value);
  console.log(ide.checkValidity());
  if(ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  }
})

标签: javascripthtml

解决方案


See HTMLSelectElement.setCustomValidity()

The HTMLSelectElement.setCustomValidity() method sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.

You're currently never resetting the custom validity message, so it remains 'Custom message: greater than 100 not allowed.' (or the other message for the other element) forever whenever an input is invalid. Insert else statements (if there is no rangeOverflow or no patternMismatch) that call setCustomValidity with the empty string to clear the error messages, in case any exist when the button is clicked:

const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input', e => {
  if (fp.validity.rangeOverflow) {
    fp.setCustomValidity('Custom message: greater than 100 not allowed.');
  } else {
    fp.setCustomValidity('');
  }
});

ide.addEventListener('input', e => {
  if (ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  } else {
    ide.setCustomValidity('');
  }
})
.u {
  margin-bottom: 15px;
}

.u:invalid {
  border: 2px solid orangered;
}

.u:valid {
  border: 2px solid greenyellow;
}

.btn {
  border: none;
  padding: 10px;
  border-radius: 8px;
  margin-top: 10px;
}

:focus {
  outline-color: gray;
}
<form action="#" method="get">
  <div>
    <label for="ide_pref">Would you prefer webstorm or vscode?</label>
    <input required class="u" type="text" pattern="webstorm|vscode" id="ide_pref" name="ide_pref"><br>
    <label for="quantity">How many licences would you like?</label>
    <input required class="u" type="number" min="1" max="100" id="quantity" name="lic_quantity"><br>
    <button class="btn" type="submit">Submit</button>
  </div>
</form>


推荐阅读