Hello,
I use Bootstrap v4.6, jQuery 3.6, select2.full.min.js 4.0.13, select2-bootstrap-theme (here) and I have form inputs which validates perfectly using checkValidity() (I followed bootstrap doc).
BUT even if my select2 has ‘required’ option, it seems always validated, even if nothing is selected.
I couldn’t find a working example code so my last chance is to post a question here, hoping for some help
Here is an excerpt from html code :
<form id="form_ajouter" class="needs-validation">
...
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="nom" class="control-label">Nom</label>
<input name="nom" type="text" class="form-control" id="nom" placeholder="Nom" required>
<div class="invalid-feedback">Ceci est obligatoire.</div>
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="option" class="control-label">option</label>
<div style="width:100%;">
<select name="option" id="option" class="form-control select2" style="width:100%;" required>
<option value='1'>item1</option>
<option value='2'>item2</option>
<option value='3'>item3</option>
</select>
<div class="invalid-feedback">Ceci est obligatoire</div>
</div>
</div>
</div>
</div>
And here is my jQuery code (I want to validate the form when I click on a button named ‘ajouter’) :
<script>
$(document).ready(function() {
$(".select2").select2({theme: 'bootstrap4'});
$('button[name="ajouter"]').on('click', function(event, state) {
var form = $("#form_ajouter")[0];
var isValid = form.checkValidity();
if (!isValid) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
return; // only for tests of course
});
});
</script>
When I click on the “ajouter” button, invalid inputs are red and help text is displayed, BUT a green border appears on the select2 where nothing is selected… That’s a problem…
Could you help me please ? Would you have a working code example using checkValidity ?
Thanks in advance for your help,
T.