0

I am trying to validating the age(i.e, greater than 18) using the angular directive. can anybody help me the validating the age?

<input type="date" data-ng-model="personalDetailsObj.personalDetails.dob"  name="dob" ng-required="true" ng-class="{ 'has-errors' : personalDetailForm.dob.$invalid, 'no-errors' : personalDetailForm.dob.$valid}" age-valid="18">

Here is my directive

.directive('ageValid', ['$filter', function($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
          ageValid: '='
        },
        link: function(scope, element, attrs) {
          scope.$watch(attrs.ngModel, function(value) {
              var todayDate = new Date(),
                  todayYear = todayDate.getFullYear(),
                  todayMonth = todayDate.getMonth(),
                  todayDay = todayDate.getDate(),
                  dateFieldVal = value;
                  console.log(dateFieldVal);
                  var formattedDate = $filter('date')(dateFieldVal,'yyyy-MM-dd');                  
                  console.log(formattedDate);

              /*var isValid = (value.length === $scope.ngLength);
              ngModel.$setValidity($attrs.ngModel, isValid);*/
          });
        } 
    }
  }])
vishnu
  • 4,377
  • 15
  • 52
  • 89

2 Answers2

7

You don't need a directive for that, you can just:

<input type="date" max="{{minAge | date:'yyyy-MM-dd'}}"/>

And your controller:

  var today = new Date();
  var minAge = 18;
  $scope.minAge = new Date(today.getFullYear() - minAge, today.getMonth(), today.getDate());

Here's a plunker

Daniel
  • 6,194
  • 7
  • 33
  • 59
1

First of all calculate age may this link help you calculate age

and then in input tag use min, max attribute to validate age.

Community
  • 1
  • 1
Ashish Kumawat
  • 685
  • 7
  • 22