I was recently tasked with validating an input field – comparing whatever someone typed with a list and making sure there aren’t any duplicates. Here’s what I did:
Install Angular-UI-Validate. I chose to use this library because of its ability to skip the hassle of writing custom formatters and easy integration with Angular. Make sure to add it as a module in app.js!
[code lang=”js”]
angular.module(‘app’, [ui.validate’])
[/code]
In the controller, I had to add a function that checked the value passed to it against a list of names.
[code lang=”js”]
$scope.nameHasNotBeenUsed = function( $value ) {
console.log($value);
if ($scope.listOfNames) { // check if the names have been loaded yet
var names = []; // for holding the names of the stacks
angular.forEach($scope.listOfNames , function(name) {
names.push(name.name); // put the names in the array
});
return names.indexOf($value) === -1; // returns true if the name doesn’t exist in the array; false otherwise
}
}
[/code]
In the view, I just had to attach a couple properties to the input: ui-validate and ng-class.
[html]
<form name="formName">
<div class="form-group">
<div class="input-group">
<input name="inputName" ui-validate=" {taken : ‘nameHasNotBeenUsed($value)’ } " ng-pattern="/^[a-zA-Z0-9-_]*$/" ng-class="{ ‘permission-input-wrong’: formName.inputName.$error.taken }" required ng-model="inputModel" type="text" class="form-control">
</div>
<span ng-show=’formName.inputName.$error.taken’>This name is already in use.</span>
</div>
</form>
[/html]
In the ui-validate property, the input is labeled as taken if the $scope.nameHasNotBeenUsed function returns false. Then, ng-class takes over: it checks for formName.inputName.$error.taken, and if it’s present, it applies the class permission-input-wrong (this just outlines the field in red).
Another cool thing we are doing is selectively hiding and showing error messages based on that formName.inputName.$error.taken.
Thanks for reading! If this helps you – if this is a dumb way of doing this, and I need to be corrected – tell me in the comments!
Cheers,
Sam