我正在使用日期指令。这是我的代码。
控制器
$scope.ageChecking = function () {
if($scope.dateOfBirth !== "Invalid Date") {
var userDate = new Date($scope.dateOfBirth);
var current_date = new Date();
var year = current_date.getFullYear();
var month = current_date.getMonth();
var day = current_date.getDate();
var dateDiff = new Date(year + "-" + month + "-" + day);
var timeDiff = Math.abs(dateDiff.getTime() - userDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var noofyears = diffDays / 365;
if (noofyears < 18) {
$scope.ageErrorMsg = "Age should be 18 years";
return false;
} else {
$scope.ageErrorMsg = "";
}
}
}
HTML
<div class="form-group"
ng-class="{'has-error':!userRegistrationForm.dateOfBirth.$valid && (!userRegistrationForm.dateOfBirth.$pristine || userRegistrationForm.$submitted)}">
<label class="control-label">DATE OF BIRTH*</label>
<div class="clearfix">
<ng-combo-date-picker name="dateOfBirth" ng-model="dateOfBirth" ng-placeholder="YYYY,MMM,DD" ng-min-date="{{minYear}}" ng-attrs-date='{"class": "form-control"}' ng-attrs-month='{"class": "form-control"}' ng-attrs-year='{"class": "form-control"}' ng-max-date="{{maxYear}}" ng-required="true" ng-year-order="desc" ng-change="ageChecking()"></ng-combo-date-picker>
</div>
<div class="help-block" ng-messages="userRegistrationForm.dateOfBirth.$error" ng-if="userRegistrationForm.$submitted || userRegistrationForm.dateOfBirth.$dirty" role="alert">
<div ng-message="required">Birth Date is required</div>
</div>
{{ageErrorMsg}}
</div>