KondukterCRO KondukterCRO - 1 year ago 68
AngularJS Question

Set custom input validation in angular form

I have an AngularJS form.
I implemented typeahead script so when someone start typing into input field values are displayed above field. If defined values are banana, apple and beer and user starts to type "ba" list appears with value banana.

If user clicks on banana value from typeahead it's assigned into input field via javascript.

I want to make input field and entire form invalid if value selected isn't from typeahead list.

I have html:

<form id="form" name="form" ng-submit="formsubmit()" novalidate>
<input ng-model="food" ng-required="true" name="food" autocomplete="off" type="text" id="food" placeholder="Start typing" />
<p class="error validationerror" ng-show="form.food.$invalid && form.food.$touched">Required</p>
<div class="error validationerror" ng-messages="form.food.$error"><p ng-message="food">You must specify item from list</p></div>
<button type="submit" id="submit" class="btn large black" ng-disabled="form.$invalid">Submit</button>
</form>


I have controller:

var app = angular.module('app', ['ngRoute', 'ngMaterial', 'ngMessages', 'angular-loading-bar']);
app.controller('Food', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.formsubmit = function () {
console.log('submited');
};

$http.get('food.php')
.success(function (data) {
$scope.foods = data;
//typeahead script...


}]);


By now everything is working ok. Now we have to check if value of input field is defined in food list. No matter if it's pasted, typed or selected from typeahead list.

I defined directive:

app.directive('food', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
function updateFoodInfo(scope, elem){
var food1 = $('#food').val();
var data = scope.foods;
if (data.indexOf(food1) < 0) {
ngModel.$parsers.unshift(function (value) {
ngModel.$setValidity('food', data.indexOf(value) === -1);
return value;
});
}
}
setInterval(function(){updateFoodInfo(scope,elem);}, 1000);
}
};
});


I have no console errors and whatever I enter into input field, form is valid. Only if I remove everything form is invalid and input field is set as invalid because it is empty. But I simply can't set custom validation.

Here is working plunker too.

plunker

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download