Custom form validation directive to compare two fields

后端 未结 6 815
借酒劲吻你
借酒劲吻你 2020-11-28 08:54

I\'m an angular newbie, and I\'m stumbling over something in how angular\'s form validation directives work.

I know that I can fairly easily add directives to in

6条回答
  •  时光说笑
    2020-11-28 09:55

    For me, beyond a feedback message, I needed define the field as invalid, preventing submit. So I gathered some approaches, like @thestewie approach, with a view configuration to gather a solution for dates comparison. I hope can aggregate the solutions that were presented.

    The code is in PLUNKER

    angular.module('MyApp')
        .directive('thisEarlierThan', function () {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function (scope, elem, attrs, ctrl) {
                    var startDate,
                        endDate;
    
                    scope.$watch(attrs.ngModel, function (newVal, oldVal, scope) {
                        startDate = newVal;
                        check();
                    });
    
                    scope.$watch(attrs.thisEarlierThan, function (newVal, oldVal, scope) {
                        endDate = newVal;
                        check();
                    });
    
                    var check = function () {
                        if (typeof startDate === 'undefined' || typeof endDate === 'undefined') {
                            return;
                        }
    
                        if (!validate(startDate)) {
                            startDate = new Date(startDate);
                            if (!validate(startDate)) {
                                return;
                            }
                        }
    
                        if (!validate(endDate)) {
                            endDate = new Date(endDate);
                            if (!validate(endDate)) {
                                return;
                            }
                        }
    
                        if (startDate < endDate) {
                            ctrl.$setValidity('thisEarlierThan', true);
                        }
                        else {
                            ctrl.$setValidity('thisEarlierThan', false);
                        }
    
                        return;
                    };
    
                    var validate = function (date) {
                        if (Object.prototype.toString.call(date) === '[object Date]') {
                            if (isNaN(date.getTime())) {
                                return false;
                            }
                            else {
                                return true;
                            }
                        }
                        else {
                          return false;
                        }
                    };
                }
            };
        })
    ;
    

提交回复
热议问题