Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form checkValidity() does not mark failed inputs

For some reasons, when I use checkValidity() on a form, the failed inputs are not marked as invalid.

The method is called this way :

var result=$("#myForm")[0].checkValidity();

When an input is invalid, result is false. But the input is not marked as invalid, there is no visual indication of the error.

I don't know if it is related, but maybe you have to know that the "required" attribute of fields is removed or added dynamically according to user's actions, with code like that :

$('input').prop('required',false);
$('input').prop('required',true);

You also have to know that I use Bootstrap 4, so the failed inputs should get the "is-invalid" class when they fail. Maybe the manipulation of the "required" property confuses Bootstrap ?

like image 585
Matt Hooper Avatar asked Feb 02 '18 13:02

Matt Hooper


2 Answers

The checkValidity-method won't add any classes to the inputs. You'll have to use the CSS-pseudoclass :invalid like

input:invalid {
    background: red;
}

to see it marked invalid. The addition/removal of "required" should work fine.

More info: https://developer.mozilla.org/de/docs/Web/CSS/:invalid

like image 115
niorad Avatar answered Nov 01 '22 09:11

niorad


I know the question has an answer but i put my answer so that it might help someone one day.

It happened to me too. In my case i changed button type="click to button type="submit inside the form and the html5 validation worked perfectly.

like image 1
jerry Avatar answered Nov 01 '22 09:11

jerry