Search code examples
angularjsangular-formly

Angular Formly - Select field should give error if option is already selected in previous select field


I am using angular formly to create form.I have dynamically added Select field and text area on Add button using angular formly repeating-section.

Requirement - From the multiple select field each Select field should have unique option selected.

How to check if option is already selected or not in previous selected field using angular formly and show error message like "Currency already selected"

Controller.js

$scope.formFields = [   {
          type: 'repeatSection',
          key: 'details',
          templateOptions: {
          btnText:'Add ',
            fields: [
              {
                className: 'row',
                fieldGroup: [
                        {
                        type: 'select', 
                        key: 'currency',
                        wrapper: 'loading', 
                     templateOptions: {
                          label: $translate.instant('CURRENCY'),
                          valueProp: "value",
                             labelProp: "name",
                           options:  [
                                {name: "Rupee", value: "INR"},
                                {name: "Doller", value: "$"},
                                {name: "Pound", value: "Pound"}
                              ] ,
                             required: true,
                             placeholder:  $translate.instant('SELECT TYPE FROM LIST'),
                         }
                       },          
                  {
                    type: 'textarea',
                    key: 'debitNote',
                    templateOptions:
                    {
                      label: $translate.instant('DEBIT NOTE'),
                      rows: 4
                    }
                  }
                ]
              }
            ]
          }

    }
];  

Solution

  • Option 1: Custom Validator

    Craft a custom validator like:

    vm.customValidator = {
      expression: function(viewValue, modelValue, scope) {
        if(scope.model.currencies){
          angular.forEach(scope.model.currencies, function(val, key) {
            if(val === modelValue) {
              console.log('Currency already selected! '+val+' === '+modelValue);
              return false;
            }
          });
        }
        return true;
      },
      message: 'Currency already selected'
    };
    

    Example: http://jsbin.com/nopike/1/edit?html,js,console,output

    *Note. Validation messages are not shown since I'm in a hurry. Please refer to the following links:

    Option 2: Multi-select

    Use Multi-select: