2

I have an AngularJS application, where I am using a HTML5 input type date control. I want to validate the control to restrict only to dates prior to today (including today).

I tried max={{new Date()}} value and tried to set, but does not seem to work.

Please suggest.

2 Answers 2

2

The best approach is to create simple dedicated validation directive that would properly add validation states to input and parent form:

angular.module('demo', [])
.controller('main', function($scope) {
    $scope.startDate = new Date('2015-12-30');
})
.directive('minDate', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController) {
            
            var minDate = scope.$eval(attrs.minDate) || new Date(new Date().setHours(0, 0, 0, 0));
            
            ngModelController.$validators.minDate = function(value) {
                return value >= minDate;
            };
        }
    };
});
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>

<div ng-app="demo" ng-controller="main">
    
    <form name="testForm">
        <input type="date" name="date" ng-model="date" required min-date="startDate" />
    </form>
    
    <div ng-if="testForm.date.$error.minDate">Select date after {{ startDate | date:'MMMM dd, yyyy' }}.</div>
</div>

This directive would be also easily reusable. Say if you want to have today as minimal date the just use min-date

<input type="date" name="date" ng-model="date" min-date />

However, you can use arbitrary date that you can pass from controller:

<input type="date" name="date" ng-model="date" min-date="startDate" />

where in controller you could have

$scope.startDate = new Date('2015-12-30');
Sign up to request clarification or add additional context in comments.

Comments

1

Firefox, which doesn't currently support type="date", will convert all the values to string. Since you (rightly) want date to be a real Date object and not a string, I think the best choice is to create another variable, for instance dateString, and then link the two variables:

<input type="date" ng-model="dateString" />
function MainCtrl($scope, dateFilter) {
    $scope.date = new Date();

    $scope.$watch('date', function (date)
    {
        $scope.dateString = dateFilter(date, 'yyyy-MM-dd');
    });

    $scope.$watch('dateString', function (dateString)
    {
        $scope.date = new Date(dateString);
    });
}

See Fidler Demo Here: Demo Link The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:

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.