I'm struggling with the HTML5 native form validation. My understanding from Client-side form validation is you can manually set the validity state of an element with setCustomValidity()
. However, this doesn't seem to override any native validation.
For example, if I have a field with required="required"
and that field is empty, it is invalid (as expected). If I call setCustomValidity('')
on that field, I would expect it to override and set it as valid, but that doesn't happen.
I then thought I could dynamically add novalidate
to the field when I want the field to be valid, but if I call checkValidity()
after adding novalidate
it still returns false
. It seems novalidate
is only good for allowing the form to be submitted regardless of the fields validity, but the field is still considered :invalid
.
Am I missing something, or is this the expected behavior? Also, is there anyway to override any default validations and manually set a field's state to :valid
? I would expect something like setValidity(true|false)
to be available in the constraint validation API.
A little more context:
I need to toggle a fields constraints based on another fields value. For example, let's say I have the following markup:
<form>
<div>Has Document?</div>
<input id="hasDocumentYes" type="radio" value="1" required="required"><label for="hasDocumentYes">Yes</label>
<input id="hasDocumentNo" type="radio" value="0" required="required"><label for="hasDocumentNo">No</label>
<label for="documentFile">Document File</label>
<input id="documentFile" type="file">
<label for="documentType">Document Types<label>
<select id="documentType"></select>
</form>
If the user selects "Yes" for "Has Document?", then I want documentFile
and documentType
to be required. The only working solution I have so far is to dynamically add the required="required"
attribute to documentFile
and documentType
when "Yes" is selected, and then manually call checkValidity()
.
This works, but it's not ideal. I have lots of these conditional validations that are not always as simple as just required or not required.
Here is the simplified example of the JS I've tried:
// if #documentFile has a required attribute and is empty, the :invalid styles
// are stilled applied after calling setCustomValidity with an empty string
$('#documentFile')[0].setCustomValidity('');
// adding a novalidate dynamically and calling checkValidity() still returns
// false if the field has the required attribute and is empty
$('#documentFile').attr('novalidate', 'novalidate');
$('#documentFile')[0].checkValidity(''); // returns false