6

I have used following code for directive which compares two dates (reference Custom form validation directive to compare two fields)

define(['./module'], function(directives) {
'use strict';
directives.directive('lowerThan', [
 function() {

   var link = function($scope, $element, $attrs, ctrl) {
   ctrl.$setValidity('lowerThan', false);
   var validate = function(viewValue) {
    var comparisonModel = $attrs.lowerThan;                

    /*if(!viewValue || !comparisonModel){
      // It's valid because we have nothing to compare against
      //console.log("It's valid because we have nothing to compare against");
      ctrl.$setValidity('lowerThan', true);
    }*/

    // It's valid if model is lower than the model we're comparing against
    //ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) <    parseInt(comparisonModel, 10) );        
    if(comparisonModel){       
        var to = comparisonModel.split("-");        
        var t = new Date(to[2], to[1] - 1, to[0]);
    }
    if(viewValue){
      var from=viewValue.split("-");
      var f=new Date(from[2],from[1]-1,from[0]);
    }

    console.log(Date.parse(t)>Date.parse(f));
    ctrl.$setValidity('lowerThan', Date.parse(t)>Date.parse(f));        
    return viewValue;
  };

  ctrl.$parsers.unshift(validate);
  ctrl.$formatters.push(validate);

  $attrs.$observe('lowerThan', function(comparisonModel){
    // Whenever the comparison model changes we'll re-validate
    return validate(ctrl.$viewValue);
  });

};

return {
  require: 'ngModel',
  link: link
};

 }
 ]);
 });

but when page is loaded first time it displays error message. i have tried using ctrl.$setValidity('lowerThan', false); to make it invisible first time. but it is not working.

Here is plunker for the same. http://plnkr.co/edit/UPN1g1JEoQMSUQZoCDAk?p=preview

Community
  • 1
  • 1
Priya
  • 1,453
  • 4
  • 29
  • 55
  • How about a fiddle...? – gkalpak Apr 26 '14 at 09:37
  • http://plnkr.co/edit/UPN1g1JEoQMSUQZoCDAk?p=preview – Priya Apr 26 '14 at 09:46
  • If the validity is set to `false` then one would expect to see an error message. If you want to check only when a button is clicked, then why do you need a directive? – a better oliver Apr 26 '14 at 09:52
  • so that same code can be used on every page – Priya Apr 26 '14 at 09:53
  • It is not clear what you are trying to achieve. You say that validation should run when you click a button, but there is no button in the fiddle. Also, it is unclear when you want the message to disappear. Why not validate on blur or something. Just putting something in a directive does not make it re-usable (especially if it does not belong in a/that directive). E.g. it makes more sense to have "validate"-button directive that takes two dates and validates them. – gkalpak Apr 26 '14 at 10:01
  • when page is loaded first time error message should not be displayed how to do that? – Priya Apr 26 '14 at 10:06

1 Answers1

9

Your directive is fine. You're setting your date values inside the controller, and you're setting the lower date to a higher value, which means the dates are invalid on load. Your directive correctly detects that. If you don't want your directive to validate your data on load, than you'll need three things:

  1. Remove the $attrs.$observe

  2. Create and apply a higherThan directive to the other field

  3. Tell your directive not to apply to the model value ($formatters array) but only to the input value ($parsers array).

PLUNKER

'use strict';
var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.field = {
    min: "02-04-2014",
    max: "01-04-2014"
  };

});

app.directive('lowerThan', [
  function() {

    var link = function($scope, $element, $attrs, ctrl) {

      var validate = function(viewValue) {
        var comparisonModel = $attrs.lowerThan;
        var t, f;

        if(!viewValue || !comparisonModel){
          // It's valid because we have nothing to compare against
          ctrl.$setValidity('lowerThan', true);
        }
        if (comparisonModel) {
            var to = comparisonModel.split("-");
            t = new Date(to[2], to[1] - 1, to[0]);
        }
        if (viewValue) {
            var from = viewValue.split("-");
            f = new Date(from[2], from[1] - 1, from[0]);
        }

        ctrl.$setValidity('lowerThan', Date.parse(t) > Date.parse(f));
        // It's valid if model is lower than the model we're comparing against

        return viewValue;
      };

      ctrl.$parsers.unshift(validate);
      //ctrl.$formatters.push(validate);

    };

    return {
      require: 'ngModel',
      link: link
    };

  }
]);

app.directive('higherThan', [
  function() {

    var link = function($scope, $element, $attrs, ctrl) {

      var validate = function(viewValue) {
        var comparisonModel = $attrs.higherThan;
        var t, f;

        if(!viewValue || !comparisonModel){
          // It's valid because we have nothing to compare against
          ctrl.$setValidity('higherThan', true);
        }
        if (comparisonModel) {
            var to = comparisonModel.split("-");
            t = new Date(to[2], to[1] - 1, to[0]);
        }
        if (viewValue) {
            var from = viewValue.split("-");
            f = new Date(from[2], from[1] - 1, from[0]);
        }

        ctrl.$setValidity('higherThan', Date.parse(t) < Date.parse(f));
        // It's valid if model is higher than the model we're comparing against

        return viewValue;
      };

      ctrl.$parsers.unshift(validate);
      //ctrl.$formatters.push(validate);

    };

    return {
      require: 'ngModel',
      link: link
    };

  }
]);
<form name="form" >

  Min: <input name="min" type="text" ng-model="field.min" lower-than="{{field.max}}" />
  <span class="error" ng-show="form.min.$error.lowerThan">
    Min cannot exceed max.
  </span>

  <br />

  Max: <input name="max" type="text" ng-model="field.max" higher-than="{{field.min}}" />
  <span class="error" ng-show="form.max.$error.higherThan">
    Max cannot be lower than min.
  </span>

</form>
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • if i change first date to 04-04-2014 then min cannot exceed max is there and then if i change second input to 05-04-2014 then min cannot exceed is not removed. is it because of removal of $attrs.$observe? – Priya Apr 28 '14 at 04:36
  • Hmm, I'm not sure how have I missed that. Yes, without the $observer your directives won't be able to track each other state. That said, I can't currently think of any elegant solution for not validating on "page load", but validating on any change between them afterwards. – Stewie Apr 28 '14 at 10:00
  • You should use moment to format the dates :) Then it's easier to handle different formats. t = moment(comparisonModel, 'DD.MM.YYYY HH:mm'); f.ex. Then you can just do. ctrl.$setValidity('lowerThan', t > f); when both t and f is a moment date ;) – stibay May 21 '15 at 16:12