Reputation: 4879
I've set a setCustomValidity()
to every input type=number
in my form to translate the default error messages.
The messages are now translated and appear when an incorrect number is inserted. The problem is that now, the error messages will always trigger on form submit even if the value is correct.
I don't know if this is a bug in HTML5 but here are the steps to replicate in this fiddle:
1234...1234
and click on submitThis is an invalid number
will appear1234
and click on submitHow can I fix this?
Upvotes: 7
Views: 2229
Reputation: 6642
Very good question buddy.
You need to clear/reset the setCustomValidity
after setting a value. But unfortunately Chrome handles .setCustomValidity
in a odd way. And because the .setCustomValidity
is handled by the browser the issue is browser dependent. Switch to full JS validation and remove parts that use .setCustomValidity
to fix the problem.
You can usually clear the setCustomValidity
by setCustomValidity('')
setting it to an empty string but it wont because the browser validates on submit which you need to override like how I have shown below
How to solve?
The trick is
Browsers must invoke the interactive validation BEFORE 'submit' event is fired. You need to reset setCustomValidity() before 'submit' event if you want a browser to show a validation message again.
$('[type=number]').on('invalid', function () {
this.setCustomValidity('This is an invalid number');
});
$('[type=number]').on('input', function () {
console.log('setCustomValidity() reset');
this.setCustomValidity('');
});
$('form').on('submit', function() {
console.log('submitted');
});
Upvotes: 8