<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<div ng-app="app" ng-controller="myCtrl">
<form novalidate name="myForm">
Your (case sensitive) input: <input type="text" name="myInput" ng-model="myInput" not-in-list="testList" />
<span style="color:red;" ng-show="myForm.myInput.$error.isInList">This is already in the list</span>
<br/>
<br/>
Your (case insensitive) input: <input type="text" name="myInput2" ng-model="myInput2" not-in-list-ignore-case="testList" />
<span style="color:red;" ng-show="myForm.myInput2.$error.isInList">This is already in the list</span>
</form>
</div>
</body>
</html>
// Code goes here
var app = angular.module("app", []);
app.controller('myCtrl', ['$scope', function($scope) {
$scope.testList = ['test', 'list', 'testing', 'invalid'];
}])
app.directive('notInList', function() {
return {
require: 'ngModel',
scope: {
notInList: '='
},
link: function(scope, element, attrs, control) {
var list;
scope.$watchCollection('notInList', function (newList, oldList) {
list = newList;
});
if(scope.notInList !== undefined){
control.$validators.isInList = function(modelValue, viewValue) {
if (control.$isEmpty(modelValue)) // if empty, correct value
{
return true;
}
if (list.indexOf(modelValue) != -1) // Is already in list value
{
return false;
}
return true; // correct value
};
}
}
};
});
app.directive('notInListIgnoreCase', function() {
return {
require: 'ngModel',
scope: {
notInListIgnoreCase: '='
},
link: function(scope, element, attrs, control) {
var list;
scope.$watchCollection('notInListIgnoreCase', function (newList, oldList) {
list = newList.map(function (value) {
return value.toUpperCase();
});
});
if (scope.notInListIgnoreCase !== undefined) {
control.$validators.isInList = function(modelValue, viewValue) {
if (control.$isEmpty(modelValue)) // if empty, correct value
{
return true;
}
if (list.indexOf(modelValue.toUpperCase()) != -1) // Is already in list value
{
return false;
}
return true; // correct value
};
}
}
};
});
/* Styles go here */