Briefly
The invalid
event triggers when attempting to submit a form with incorrect values. For example, if one of the required fields is not filled.
<input type="text" required>
<input type="text" required>
How to write
You can subscribe to invalid
and react, for example, by outputting a phrase or an array with incorrect data to the console:
const gandalf = document.querySelector('input')gandalf.addEventListener('invalid', (event) => { console.log('You shall not pass!')})
const gandalf = document.querySelector('input') gandalf.addEventListener('invalid', (event) => { console.log('You shall not pass!') })
How to understand
The invalid
event triggers after the submit
event during form field validation if the value in one of the fields does not meet the condition.
If you enter the value 6
in the form below, the invalid
event will trigger because the field has a check max
:
<form> <label for="input-containter"> Enter the number of bees from 1 to 5: </label> <input id="input-containter" type="number" min="1" max="5" required></form><div> <button type="submit" value="submit"> Get honey </button></div>
<form> <label for="input-containter"> Enter the number of bees from 1 to 5: </label> <input id="input-containter" type="number" min="1" max="5" required> </form> <div> <button type="submit" value="submit"> Get honey </button> </div>
const input = document.querySelector(`input`)input.addEventListener('invalid', (event) => { alert('Wrong bee!')})
const input = document.querySelector(`input`) input.addEventListener('invalid', (event) => { alert('Wrong bee!') })
You can customize how form validation errors will be displayed.