Integrating with MagicSuggest

This example demonstrates how to integrate FormValidation with MagicSuggest. It's a jQuery plugin that shows a multiple selection dropdown which options can be passed from a given data source.
The MagicSuggest plugin attaches a given element, not an input. That's why we need to prepare a hidden field to track which options are chosen:
<form id="demoForm">
<!-- The hidden field -->
<input type="hidden" name="dest" />
<!-- The area that MagicSuggest attaches to -->
<div id="destination"></div>
...
</form>
We can apply a few of validators for the hidden field. Let's say that it can't be empty:
const demoForm = document.getElementById('demoForm');
const fv = FormValidation.formValidation(demoForm, {
fields: {
dest: {
validators: {
notEmpty: {
message: 'Please choose one city'
}
}
},
},
plugins: {
...
},
});
Now, all the preparations are done. It's the time for us to integrate MagicSuggest with the destination element above:
const destinationEle = jQuery('#destination').magicSuggest({
data: ['Amsterdam', 'Barcelona', 'Hanoi', 'London', 'New York', 'Paris', 'Rome', 'San Francisco', 'Seoul', 'Tokyo'],
maxSelection: 1,
});
To make the demonstration simple, the data source is just a list of string. In reality, it can be an URL that fetches data from your back-end. Currently there is no connection between the hidden field and our destination dropdown.
What we wish are
It can be done by triggering the MagicSuggest's selectionchange event and the FormValidation's revalidateField() method. The following piece of code illustrates that approach:
jQuery(destinationEle).on('selectionchange', function (e, m) {
// Get the selected item
const data = this.getSelection();
// Update the value for hidden field
destField.value = data.length == 0 ? '' : data[0].name;
// Revalidate the field
fv.revalidateField('dest');
});
You should look at the basic principle when integrating FormValidation with 3rd party libraries
Integrating with MagicSuggest
The demonstration also uses the technique introduced in the Adjusting icon position example, so the feedback icon is displayed at the desired position

See also