问题
My form contains a selectize and a Bootstrap toggle button group. Both fields are mandatory (so the required rule holds for both fields).
HTML:
<form role="form" id="form">
<div class="form-group">
<div class="form-group shiny-input-container">
<div>
<label for="coin">Choose:</label>
</div>
<div id="coin" class="btn-group-toggle btn-group" data-toggle="buttons">
<label class="btn ">heads
<input type="radio" value="heads" name="coin"/>
</label>
<label class="btn ">tails
<input type="radio" value="tails" name="coin"/>
</label>
</div>
</div>
</div>
<div class="form-group">
<select id="name" placeholder="Select a person..." name="name">
<option value="">Type a name...</option>
<option value="xerxes">Xerxes</option>
<option value="darius">Darius</option>
<option value="cyrus">Cyrus</option>
</select>
</div>
<button id="submit" type="button" class="btn btn-default action-button">submit</button>
</form>
JS:
$(function() {
$('#name').selectize();
$("#form").validate({
ignore: [],
rules: {
coin: {
required: true
},
name: {
required: true
}
}
});
$("#submit").click(function() {
$("#form").valid();
});
//Using `change` event to force eager validation
$('.selectized, label.btn>input').change(function() {
$(this).valid();
});
});
See JSFiddle
The actual input tags of these components are hidden (e.g. in the Bootstrap button group, each checkbox is contained within a label tag and is therefore not visible in the DOM) so I use ignore: [] to tell jQuery Validate not to ignore them.
Validation works fine when the form is submitted when the user hits 'Submit' - if a field is empty upon submission, an error message is displayed next to it as expected.
The problem is that the fields are not eagerly validated - once the user has filled in a field that was empty when the form was initially submitted, that field is not revalidated (you can see in the demo that the error message persists even after the field receives input).
To force revalidation, I can use the change event listener as follows:
//Eager validation of selectize
$('.selectized').on('change', function() {
$(this).valid();
});
//Eager validation of toggle button group
$('label.btn>input').on('change', function() {
$(this).valid();
});
But this seems hacky and I was wondering if there was a more general solution - one that doesn't require foreknowledge of which inputs need forced eager validation?
I would also like to better understand why these fields aren't being eagerly validated. I think it might have something to do with the jQuery Validate's default event listeners (focusin, focusout, keyup, click) not being able to capture a change in these inputs since they are not visible in the DOM? I'm new to web development so any insight would be much appreciated.
来源:https://stackoverflow.com/questions/62914388/jquery-validate-eager-validation-of-selectize-js-and-bootstrap-btn-group-togg