I have a special validation directive that I use to ensure that two dates are in the valid range. The directive works fine when the user changes the values, however it does not start when I load the new lineItem model through AJAX.
The problem is that the user may enter invalid dates on the form and cause an error, and then load another lineItem file. At this point, an error message appears in the form, even if the data in the form is valid.
If I try to do the same with Angular built into validation (e.g. required ), then the check starts and disappears accordingly. So what do I need to make my check run just like Angular?
(note: I am using novalidate for the form attribute and Angular v1.1.5)
DIRECTIVE
ngApp.directive("validateBefore", function () { return { require: 'ngModel', link: function (scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(value) { var before = scope.$eval(attrs.validateBefore); if(value <= before || !before) { ctrl.$setValidity("validateBefore", true); return value; } else { ctrl.$setValidity("validateBefore", false); return undefined; } }); } } });
TEMPLATE
<div class="date-group"> <span class="date"> <input type="text" class="input-medium" name="starts-at" ng-model="lineItem.startsAt" placeholder="From..." validate-before="lineItem.endsAt"> </span> <span class="date"> <input type="text" class="input-medium" name="ends-at" ng-model="lineItem.endsAt" placeholder="To..." validate-after="lineItem.startsAt"> </span> </div>
CONTROLLER
var lineItem = LineItem.get( { id: lineItemId }, function () { $scope.lineItem = lineItem; if($scope.lineItemForm) { $scope.lineItemForm.$setPristine(); } }
Mike robinson
source share