Date input validation using ng-change, AngularJS

Reza Shayestehpour picture Reza Shayestehpour · May 11, 2014 · Viewed 24.7k times · Source

I's using AngularJS and AngularJS bootstrap in my page. I have a date picker directive that looks like this:

    <div class="form-group {{dateStatus.class}}">
        <p class="input-group">
            <input type="text" id="inpDate" class="form-control" 
                   datepicker-popup="dd-MMMM-yyyy" ng-model="task.date" 
                   is-open="datePickerStatus.isOpen" min-date="minDate" 
                   datepicker-options="dateOptions" ng-required="true" 
                   close-text="Close" placeholder="Due date" 
                   ng-change="checkDateValidity()"
            />
            <span class="input-group-btn">
                <button type="button" class="btn btn-default" 
                        ng-click="openDatePicker($event)"
                >
                    <i class="glyphicon glyphicon-calendar"></i>
                </button>
            </span>
        </p>
    </div>

To validate the date input, in my controller I have the following function:

        $scope.checkDateValidity = function(){
        var date,
            isValid,
            taskDate;
        taskDate = $scope.task.date;
        date = new Date(taskDate);
        isValid = !isNaN(date);
        if(isValid) {
            $scope.addButtonState.isOk = true;
            $scope.dateStatus.class = '';
        }
        else{
            $scope.addButtonState.isOk = false;
            $scope.dateStatus.class = 'has-error';
        }
    }

everything works fine for checking if the date inserted is valid, but the problem is that when the date input is left blank(or changed from a valid state to blank) I want it to be acceptable too, but since both empty input and invalid date are undefinedI don't know how to declare between the cases.

I also thought of reading the input text directly like this:

document.getElementById('inpDate').value

but the ng-change is fired when the value is changed and I'm left with the previous value which is useless now...

thanks for your time and response.

Answer

Andy59469 picture Andy59469 · May 27, 2015

A much better way of validating is using a directive to add a Validation Rule.

.directive("validateDate", function() {
     return {
         require: 'ngModel',
         link: function(scope, elm, attrs, ctrl) {
             ctrl.$validators.validateDate = function(modelValue, viewValue) {
                 if(!isNaN(modelValue) || ctrl.$isEmpty(modelValue)){
                     return true;
                 }
                 return false;
             };
         }
     };
 })

then you just need to add validate-date to the input tag and the validation will mark the input as valid if it is !isNaN (when the date is a number OR is empty)