CIRCLE CIRCLE - 2 months ago 21
HTML Question

HTML5 form validation triggering on correct value after setting setCustomValidity

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:


  • Inset the value
    1234...1234
    and click on submit

  • A message saying
    This is an invalid number
    will appear

  • Now insert just
    1234
    and click on submit

  • The same message appears even when the value is a valid number



How can I fix this?

Answer

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 removed 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

Fiddle here

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');
});
Comments