How do i prevent duplicate values with multiselect

When I’m trying to select single option which value attribute that is not unique (1st screen), all options with same value are inserting to my select.

This results in that (2st screen):
image
Such invalid behavior ignores select2 configuration: I have a limit on the amount of selections.

I’m using angularJs with ui-select2 wrapper for select2 (obsolete version) in the app. Here’s module which is responsible for creation select2.

angular.module("anketaApp.selectList", ['ui.select2']).directive("selectList",
    function ($compile, $http) {
        return function (scope, element, attrs) {

            //....

            scope.select2Options = {
                
                allowClear: scope.cell.allowBlank,
                maximumSelectionLength: 5,
                
            };

            var $content =
                $('<select ui-select2="select2Options" custom-validation ng-disabled="cell.predeterminedValue" name="singleSelect" ng-model="cell.val" >' +
                    '<option ng-if="cell.allowBlank"></option>' +
                    '<option ng-repeat="option in data" value="{{option.Key}}">{{option.Value}}</option>' +
                    '</select>');

            var selectElement = angular.element($content);

            var compileFn = $compile(selectElement);
            compileFn(scope);

            element.append(selectElement);

            //....
        };
    }).directive('customValidation', 
    function () {
        return {
            require:'ngModel',
            link: function (scope, element,attrs, model) {
                    $(element).on("select2:selecting",
                        function (e) {
                            e.preventDefault();
                         
                            var val = $(this).val() || [];
                            val.push(e.params.args.data.text);
                            $(element).val(val).trigger('change');
                            $(element).select2("close");
                        });
          }
        };
    });

customValidation directive tries to insert selecting value programmatically, but result is the same.

How can i fix it? Thanks in advance

Select2 requires that each option has a unique value (to prevent exactly the behavior you have described). It appears that all of your <option>s have the same “value” property (which seems odd to me). If that’s truly how your data is structured (that they all have the same “Key” value), then you will need to compute a “surrogate key” that you can insert into each <option>'s “value” property. Since it appears your “Value” property is unique, I would suggest setting the <option>'s “value” property to something like value="{{option.Value}}:{{option.Key}}", and then you can filter out the first part in your custom validation logic.