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);*/
          });
        } 
    }
  }])
1
  • 1
    Can you add any fiddle/plnkr? Commented Dec 21, 2015 at 5:50

2 Answers 2

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

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

Comments

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.

Comments

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.