how to validate date format in angular

24,715

Solution 1

I update your FormValidator function to use native JavaScript

var formValidator = function ($scope) {
    var isDateValid = function () {
        //return $scope.model != null && $scope.model.date != null && $scope.model.date !== '';
        var dateTime = $scope.model.date;
        if (dateTime === null) return false;
        var day = dateTime.getDate();
        var month = dateTime.getMonth() + 1;
        var year = dateTime.getFullYear();
        var composedDate = new Date(year, month, day);
        return composedDate.getDate() === day &&
                 composedDate.getMonth() === month &&
                 composedDate.getFullYear() === year;

    };

    return {
        valid: function () {
            var isValid = true;
            if (!isDateValid()) {
                isValid = false;
            }

            return isValid;
        },
        addWatches: function () {
            $scope.$watch('model.date', function () {
                $scope.displayModel.showDateValidator = !isDateValid();
            });

        }
    };

};//ActivitiesFormValidator

Solution 2

Momentjs library might be useful for you.

moment("2010 13",           "YYYY MM").isValid();     // false (not a real month)
moment("2010 11 31",        "YYYY MM DD").isValid();  // false (not a real day)
moment("2010 2 29",         "YYYY MM DD").isValid();  // false (not a leap year)
moment("2010 notamonth 29", "YYYY MMM DD").isValid(); // false (not a real month name)

Solution 3

Use native static Date.parse() method or take a look at momentjs library, which has great date abstraction over it.

Also you can use regular expression to check your date, e.g.

/\d{4}-\d{2}-\d{2}/.test($scope.model.date)

but it should come in the pair with Date.parse, couse 9999-99-99 will pass through such simple validator.

Anyway, here some regexps for date validation to look at.

Share:
24,715
Admin
Author by

Admin

Updated on May 14, 2020

Comments

  • Admin
    Admin almost 4 years

    Hi just I was wondering about problem for example if I have angular UI date piker date format yyyy-MM-dd .what if the users enter date by typing and they enter wrong format for example yyyy-dd-mm the app think it is valid date and save it as YYYY-MM-dd. just how can I validate format it is correct ?

    <div class="panel panel-default">
        <div class="panel-heading">Date </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="control-label"><i class="fa fa-calendar"></i><i class="icon-required"></i>Date [YYYY-MM-DD]</label>
                        <div class="input-group">
                            <input type="text" class="form-control" datepicker-popup="yyyy-MM-dd" data-ng-model="model.date" is-open="isDatePickerOpen" close-text="Close" />
                            <span class="input-group-btn">
                                <button type="button" class="btn btn-default" data-ng-click="openDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>
                            </span>
                        </div>
                        <div class="validation-warning" data-ng-show="displayModel.showDateValidator"><i class="icon-alert"></i>Required</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    validator

    var formValidator = function ($scope) {
        var isDateValid = function () {
            return $scope.model != null && $scope.model.date != null && $scope.model.date !== '';
        };
    
        return {
            valid: function () {
                var isValid = true;
                if (!isDateValid()) {
                    isValid = false;
                }
    
                return isValid;
            },
            addWatches: function () {
                $scope.$watch('model.date', function () {
                    $scope.displayModel.showDateValidator = !isDateValid();
                });
    
            }
        };
    
    };//ActivitiesFormValidator
    
  • java-addict301
    java-addict301 almost 5 years
    "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent" - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Anton Savchenko
    Anton Savchenko almost 5 years
    @java-addict301 c'mon, what year are you leaving in? there is es2019 already
  • java-addict301
    java-addict301 almost 5 years
    Hey, I'm just the messenger - take it up with Mozilla if you disagree. It states that "There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated)."