结束日期必须大于使用angularjs的开始日期验证

时间:2014-05-15 10:52:06

标签: javascript angularjs

我想创建一个验证方向来验证更大的结束日期而不是开始,我创建了类似这样的工作正常如果我先输入开始日期然后结束日期。如果我键入结束日期然后键入第一个日期,则此规则不起作用。我该如何解决?

.directive('dateGreaterThan', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            var sc = scope;
            scope.$watch(attrs.ngModel, function() {
                var eqCtrl = scope.$eval(attrs.dateGreaterThan);
                //assuming pattern 'mm-dd-yyyy HH:MM:SS'
                var v1 = ctrl.$viewValue;
                var v2 = eqCtrl.$viewValue;

                if(v1 && v2) {
                    var ctrlDate = new Date(v1.substr(6,4) + '-' + v1.substr(0,2) + '-' + v1.substr(3,2) + 'T' + v1.substr(11));
                    var eqCtrlDate = new Date(v2.substr(6,4) + '-' + v2.substr(0,2) + '-' + v2.substr(3,2) + 'T' + v2.substr(11));
                    if (ctrlDate > eqCtrlDate) {
                        ctrl.$setValidity('dateGreaterThan', true);
                    } else {
                        ctrl.$setValidity('dateGreaterThan', false);
                    }
                }

            });
        }
    };
});

这是html代码

<input id="start" name="start" ng-model="start" type="text"
   class="form-control" placeholder="mm-dd-yyyy hh:mm:ss" required>

<input id="end" name="end" ng-model="end" type="text"
   class="form-control" placeholder="mm-dd-yyyy hh:mm:ss" required   
   date-greater-than="myForm.start">
<label ng-show="myForm.end.$error.dateGreaterThan" class="error">End date must be larger than start date</label>

0 个答案:

没有答案