1

There can be 1 or more inputs. All inputs must have different values. How to create such validation(directive)? If user enters non-unique value in some input - it should be highlighted as invalid.

For now I just have html template without validation

<form name="myForm" id="myForm">
                <md-input-container ng-repeat="(key, item) in data">
                    <label>{{labels[item.id]}}</label>
                    <input ng-model="data[key].number" required>
                </md-input-container>

                <md-button ng-click="save()" class="md-raised md-button md-primary" ng-disabled="myForm.$invalid">
                    Save
                </md-button>
            </form>

Update. I managed to solve this with ng-change directive:

Template is the same except:

<input ng-model="data[key].number" name="number_{{key}}" required ng-change="validate(key, myForm)">

validate function in controller:

$scope.validate = function(key, myForm) {
        for (let i = 0; i < data.length; i++) {
            if(i == key) continue;

            if(data[i].number === data[key].number){
                myForm['number_' + key].$setValidity("unique", false);
                return;
            }else{
                myForm['number_' + key].$setValidity("unique", true);
            }
        }
    };
3
  • Looks like your homework, no? please show your code Commented May 18, 2020 at 7:47
  • @MaximShoustin For now I just have html template without validation (edited question) Commented May 18, 2020 at 7:56
  • can u please post an example of data list? Commented May 18, 2020 at 9:38

2 Answers 2

1

I would use ng-change instead of a directive. You can pass controlName and inputValue into your function and can do proper validation

Sign up to request clarification or add additional context in comments.

Comments

1

You can write some directive that blocklist prev typed values.

Something like:

app.directive('blacklist', function (){ 
   return {
      require: 'ngModel',
      link: function(scope, elem, attr, ngModel) {
          var blacklist = attr.blacklist.split(',');
          ngModel.$parsers.unshift(function (value) {
            // here you can parse the data
             ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
             return value;
          });
      }
   };
});

and:

 <input ng-model="data[key].number" blacklist="data" required>

Some Demo

It will give you some insight

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.