Angular: Validation directive
http://angularjs.org/
by hanspc
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">Please enter two integers:<br>
Int 1: <input type="text" ng-model="int1"><br><br>
Int 2: <input ng-class="int2valid" type="text" ng-model="int2" validate-integer><br>
<span ng-hide="int2valid=='valid'" style="color: red">Int 2 must be higher than Int 1</span>
<br><br><br><br><br><br><br><br>
If Int 1 changes after the Int 2 field was validated the validation doesn't run until the values in Int 2 changes. Ie: Set Int 1 to 2, Int 2 to 3, and then change Int 1 to 5. Int 2 will still be marked as valid, even though it really isn't.
</div>
JavaScript
var myApp = angular.module('myApp', [])
.directive('validateInteger', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
var int1val = scope.int1;
scope.int2valid = (viewValue > int1val) ? "valid" : undefined;
if (scope.int2valid == "valid") {
ctrl.$setValidity('higher', true);
return viewValue;
} else {
ctrl.$setValidity('higher', false);
return undefined;
}
});
}
};
});
function MyCtrl($scope) {
}