Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 and HTML5 form validation

How I can do a form validation (HTML5 Required) with Select2?

like image 861
Nizar Avatar asked Sep 23 '13 09:09

Nizar


2 Answers

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);
}
like image 110
Zach Painter Avatar answered Sep 20 '22 02:09

Zach Painter


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

like image 33
zizoujab Avatar answered Sep 21 '22 02:09

zizoujab