2

I have an html form that looks like this :

<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 am trying to validate input for Age field when it blurs out.Age value should be between 3 to 99.i.i.e check if the value is valid or invalid when user is done typing and leaves the text field.Then if the value is invalid, apply the has- class The directive though is not working. Did I miss anything ?

8
  • any console errors? what exactly isn't working? Commented Jul 8, 2015 at 8:23
  • No, No console error. I have not been able to figure that out yet. Commented Jul 8, 2015 at 8:24
  • What do you expect to happen, and what is actually happening? Commented Jul 8, 2015 at 8:24
  • I am trying to invalidate user input in Age field when user takes cursor off the field ,in case the age value is smaller than 3 or great than 99. Commented Jul 8, 2015 at 8:26
  • it looks like you are trying to add a class which blurs out the input field if the information is entered incorrectly? and you want this validation to take place only after the user takes cursor off the input? Commented Jul 8, 2015 at 8:30

3 Answers 3

3

If really have to do that 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 your 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>

Sign up to request clarification or add additional context in comments.

Comments

2

AngularJS 1.3.x introduces $validators pipeline - it is much simpler to write custom validation rules with them.

A collection of validators that are applied whenever the model value changes. The key value within the object refers to the name of the validator while the function refers to the validation operation. The validation operation is provided with the model value as an argument and must return a true or false value depending on the response of that validation.

var app = angular.module('app', []);

app
  .controller('MainCtrl', function($scope) {
    $scope.name = 'World';
  }).directive('ngAge', function NgLength() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, $element, $attrs, ngModel) {
        ngModel.$validators.validAge = function(modelValue, viewValue) {
          var age = modelValue || viewValue;
          return age > 3 && age < 100
        };
      }
    }
  });
.has-error {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/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

1

You can use max, min directive. Please sample below

var app = angular.module('plunker', []);
.has-error {
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<html ng-app="plunker">



<body>

  <div class="row col-lg-offset-3">
    <form name="userForm" 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="number" class="form-control" name="Age" ng-model="user.Age" ng-required='!user.phonenumber' placeholder="Age" max="100" min="3" />
   
  </form>
  </div>

2 Comments

Thank you but it's a requirement to do it via custom directive only as I am learning to use them.
@simikaur please see answer below

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.