2
votes

I have two major problem regarding HTML5 form validation.

1- I use this code to change the validation message of inputs

$$('INPUT').each(function(input) 
{    
  input.oninvalid = function(event) 
  {
     event.target.setCustomValidity('');
     if (!event.target.validity.valid) event.target.setCustomValidity('Please Fill');
  };
}

There's a big problem with this method. As the form is submitted if the input is invalid, an error message is attached to it. So it wouldn't validate on new input. Even after correction and submitting again it won't let the form get submitted because the message is still attached. so event.target.setCustomValidity('') will remove the message and form needs another submit. two submit after correction.

I couldn't find a way to correct this behavior.

2-How can I hide or disable these tooltips totally but still use form validation. Sometimes I want to use css invalid and valid pseudo classes, but these tips are still displayed.

I find formnovalidate on submit button and then I can check validity.valid of each inputs manually before submitting. any better idea?

1
Why not clear the "custom validity" flags on the next "change" event (or even "keyup" or any other interaction)? - Pointy
Handling the results of using the "setCustomValidity()" API. If you clear the string as soon as the user starts interacting with the form, you would avoid the double-submit problem. - Pointy
I will test it. Do you know any good resource about HTML5 Validation. I found some, but most of them are general. - Ali
The MDN page is pretty good. It's a simple system, which I think is partly what makes it confusing. - Pointy
Can you put your code in a jsFiddle. This example is doing essentially the same thing as your code, but it doesn't require double submission. - robertc

1 Answers

0
votes

In terms of question 1:

I had an input

<input name="VoucherCode"  id="VoucherCode"  type="text" pattern="(1[0-9]{9})|(2[0-9]{9})" value="">

And improved the default message

$("#VoucherCode").on("invalid", function (event) {
    event.target.setCustomValidity('The format of Voucher Code is not correct.')
});

But this had the same problem you encountered: if the user gets the first attempt wrong, a correct response still show the invalid pattern message.

I fixed this based on @Pointy's suggestion:

$("#VoucherCode").on("invalid", function (event) {
    event.target.setCustomValidity('The format of Voucher Code is not correct.')
}).bind('blur', function (event) {
    event.target.setCustomValidity('');                
});