简体   繁体   中英

AngularJS custom directive for form validation for date inputs

I have an app written in Angular 1.5.3.

Here is what I want to do:

I have a user form with 2 date input types. I need to add some custom validation to my form. I want to show an error message to the user when the "expiry date" on the form is greater than the "effective date" on the form.

I believe that I can do this with a custom directive and with ng-messages.

Here is my code snippet:

 <form name="form.mainForm">

      <div>
        <span>Effective Date: </span>
        <input required type="date" name="effectiveDate" ng-model="effectiveDate" />

        <div>
          <span>Expiry Date: </span>
          <input 
            type="date" 
            name="expiryDate" 
            ng-model="expiryDate" 
            date-greater-than="{{ effectiveDate }}" />
        </div>
      </div>
  </form>


app.directive('dateGreaterThan', function () {
      return {
                restrict: 'A',
        require: 'ngModel',
        scope: false,
        link: function (scope, elm, attrs, ctrl) {
            console.log(' here we are ');

            function isValidDateRange(expiryDate, effectiveDate) {

                console.log(expiryDate, effectiveDate);

                if (effectiveDate == null || expiryDate == null ) {
                    return true;
                }

                return effectiveDate > expiryDate;
            }

            function validateDateRange(inputValue) {
                var expiryDate = inputValue;
                var effectiveDate = scope.effectiveDate;
                var isValid = isValidDateRange(expiryDate, effectiveDate);
                console.log("isValid: ", isValid);
                ctrl.$setValidity('dateGreaterThan', isValid);
                return inputValue;
            }

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateGreaterThan', function () {
                validateDateRange(ctrl.$viewValue);
            });
      }
      };

I have attempted to solve the problem here but I can't get my directive to work properly. It doesn't seem to calculate the dates when they change and it doesn't integrate with ng-messages.

Here's my attempt: http://jsfiddle.net/aubz88/q7n3abre/

The ngMessages module should be loaded from a cdn. Or installed with a package manager. The ngMessages module is not included in AngularJS. https://code.angularjs.org/1.4.14/docs/api/ngMessages

var app = angular.module("hello", ['ngMessages']);

Some other points. Use the $validators from the ngModel.

ctrl.$validators.dateGreaterThan = validateDateRange;

Pass the other date with a scope property

 scope: {dateGreaterThan: '='},

There is still a lot to improve I think. I did forgot some AngularJS stuff too. fe: you could trigger the validation again when the first date changes. Check the $validate function of https://code.angularjs.org/1.4.14/docs/api/ng/type/ngModel.NgModelController .

You can check this fiddle for a basic setup: http://jsfiddle.net/hcjLkuzt/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM