AngularJs dynamic form validation – Unique items, mark both invalid

posted in: AngularJS, Form Validation | 0

http://stackoverflow.com/questions/25909167/angularjs-how-to-check-for-unique-inputs-and-if-there-is-a-duplicate-mark-both

 

Problem: 

a user needs to enter input into text areas created by ng-repeat. If the user enters a value that has already been entered both the new and existing values should be validated as false. If one of the values (existing or new) gets changed, the validation should be updated correspondingly.


 

$scope.verifyDuplicate = function() {
        var sorted, i;
        sorted = $scope.persons.concat().sort(function (a, b) {
            if (a.name > b.name) return 1;
            if (a.name < b.name) return -1;
            return 0;
        });
        for(i = 0; i < $scope.persons.length; i++) {
            sorted[i].isDuplicate = ((sorted[i-1] && sorted[i-1].name == sorted[i].name) || (sorted[i+1] && sorted[i+1].name == sorted[i].name));
        }
    };

JSFiddler: http://jsfiddle.net/luislee818/pkhxkozp/4/


 

If you insist of using the $setValidity function:

$scope.verifyDuplicate = function() {
        var sorted, i, isDuplicate;
        sorted = $scope.persons.concat().sort(function (a, b) {
            if (a.name > b.name) return 1;
            if (a.name < b.name) return -1;
            return 0;
        });
        for(i = 0; i < $scope.persons.length; i++) {
            isDuplicate = ((sorted[i-1] && sorted[i-1].name == sorted[i].name) || (sorted[i+1] && sorted[i+1].name == sorted[i].name));
            sorted[i].form.personName.$setValidity('duplicate',!isDuplicate);
        }
    };

JSFiddle: http://jsfiddle.net/luislee818/nzd87f1s/1/

 

Thanks for AVN for the research for this answer.

 

Leave a Reply