I'm using code example of Select2 plugin to validate a multiple select field. I just want that the field has at least one element.
Here my code:
HTML:
<div class="form-group row">
<label for="roles" class="col-sm-3 col-form-label">{{ ucfirst(trans_choice("configurazione.ruoli",2)) }}</label>
<div class="col-sm-9">
<select name="roles[]" id="roles" class="form-control select2" multiple="">
@foreach($ruoli as $ruolo)
<option value="{{ $ruolo->id }}" {{ isset($utenti) ? (in_array($ruolo->id, $ruoliUtenti) ? "selected" : "") : "" }}>{{ $ruolo->name }}</option>
@endforeach
</select>
<div class="invalid-feedback">{{ __("validation.filled", ['attribute' => trans_choice("configurazione.ruoli",1)]) }}</div>
</div>
</div>
JS:
document.addEventListener('DOMContentLoaded', function (e) {
const userForm = document.getElementById('userForm');
const rolesField = jQuery(userForm.querySelector('[name="roles"]'));
const fv = FormValidation.formValidation(
userForm,
{
locale: 'it_IT',
localization: FormValidation.locales.it_IT,
fields: {
'roles[]': {
validators: {
callback: {
callback: function (input) {
// Get the selected options
const options = rolesField.select2('data');
return options != null && options.length < 1;
},
},
}
},
},
plugins: {
submitButton: new FormValidation.plugins.SubmitButton(),
defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
bootstrap: new FormValidation.plugins.Bootstrap(),
excluded: new FormValidation.plugins.Excluded(),
// Show the feedback icons taken from FontAwesome
icon: new FormValidation.plugins.Icon({
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh',
}),
}
}
);
rolesField.select2().on('select2.change', function () {
fv.revalidateField('roles[]');
});
});
When I try to submit the form with empty value, it works, but after that, if I fill the field, the 'revalidateField' seems to not work.
I tried with:
fv.revalidateField('roles[]');
or
fv.revalidateField('roles');
Where is my error?
UPDATE
I added an alert to view the options data returned but it always returns "undefined".
const options = rolesField.select2('data');
alert(options);
The issue is the revalidator won't work with the form select named "roles[]" that is also a select2 element.
The workaround is to implement some code I found here. And then have your post code work with the newly formed request data. (which is to pull the raw PHP input and convert that to the request data on the server side)