We can set custom HTML5 required field validation messages with the setCustomValidity
method.
For instance, if we have the following input:
<form>
<input type="email" pattern="[^@]*@[^@]" required />
<input type="submit" />
</form>
Then we can set a custom validation message by writing:
const input = document.querySelector('input')
input.addEventListener('invalid', (e) => {
e.target.setCustomValidity('Put here custom message')
})
We get the input with document.querySelector
.
Then we listen to the invalid
event with addEventListener
.
Then we call e.target.setCustomValidity
on it with our own validation error message.
e.target
is the input
element since we called addEventListener
on the input
.