How I can do a form validation (HTML5 Required) with Select2?
Yes validation will work as expected with the select2 element... This is because underneath the form is still using your original input...
If you want to style the Select 2 multi select display using html 5 pseudo elements :valid
and :invalid
you will need to do something like this..
select:invalid + .select2-container > span.selection > span.select2-selection {
border-color: #dc3545;
}
select:invalid + .select2-container--focus > span.selection > span.select2-selection {
border-color: #dc3545;
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}
select:valid + .select2-container > span.selection > span.select2-selection {
border-color: #28a745;
}
select:valid + .select2-container--focus > span.selection > span.select2-selection {
border-color: #28a745;
box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}
This gives a bootstrap styling for valid and invalid elements.
I use bootstrap in my projects so I went a bit further with the styling rules:
.was-validated select.form-control:invalid + .select2-container > span.selection > span.select2-selection {
border-color: #dc3545;
}
.was-validated select.form-control:invalid + .select2-container--focus > span.selection > span.select2-selection {
border-color: #dc3545;
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}
.was-validated select.form-control:valid + .select2-container > span.selection > span.select2-selection {
border-color: #28a745;
}
.was-validated select.form-control:valid + .select2-container--focus > span.selection > span.select2-selection {
border-color: #28a745;
box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}
This may be a late answer but anyway : you just add a required to the select and the html5 validation will show up :
Fiddle : http://jsfiddle.net/mksshhwt/
<form>
required select2: <select class="select2" required multiple name="test">
<option>Test</option>
<option>Test2</option>
</select>
<br/>
required select2: <select class="select2" required name="test">
<option>Test</option>
<option>Test2</option>
</select>
<br/>
<input type="submit" value="Test" />
</form>
JS :
$(".select2").select2();
you may get the validation a little on the top , follow this thread to fix it : https://github.com/select2/select2/issues/128
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With