AngularJS - write custom directive to validate passed values -
i have html form looks :
<div class="row col-lg-offset-3"> <div class="form-group col-lg-6" ng-class="{ 'has-error': userform.age.$invalid && userform.age.$dirty}" show-errors > <label class="control-label">age</label> <input type="text" class="form-control" name="age" ng-model="user.age" ng-required='!user.phonenumber' placeholder="age"/> </div> </div>
directive:
(function(){ angular.module('myapp', []) .controller('studentdatacontroller', function($scope) {}) .directive('showerrors', function() { return { restrict: 'a', require: '^form', link: function (scope, el, attrs, formctrl) { var inputel = el[0].queryselector("[age]"); var inputngel = angular.element(inputel); var inputvalue = inputngel.attr('age'); var isvalid = (inputvalue >= 3 && inputvalue < 100); inputngel.bind('blur', function() { el.toggleclass('has-error', isvalid); }) } } }); })();
i trying validate input age field when blurs out.age value should between 3 99.i.i.e check if value valid or invalid when user done typing , leaves text field.then if value invalid, apply has- class directive though not working. did miss ?
if have via custom directive please see below:
var app = angular.module('app', []); app.controller('mainctrl', function($scope) { $scope.name = 'world'; }); app .directive('ngage', nglength); function nglength() { return { restrict: 'a', require: 'ngmodel', link: function($scope, $element, $attrs, ngmodel) { $scope.$watch($attrs.ngmodel, function(value) { var isvalid = (value > 3 && value < 100); ngmodel.$setvalidity($attrs.ngmodel, isvalid); }); } } }
/* put css in here */ .has-error { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app"> <form name="userform" ng-class="{ 'has-error': userform.age.$invalid && userform.age.$dirty}"> <label class="control-label">age</label> <input type="text" class="form-control" name="age" ng-model="user.age" ng-age placeholder="age" /> </form> </body>
Comments
Post a Comment