1

I have a directive designed to impose date range restrictions on a date input field (earliest and latest). Here is the directive below, I am using the momentjs library to do my date comparison:

.directive('startDate', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {
        console.log(arguments);
        var compareStartDates = function (value) {
            var startDateCompare = moment((attrs.startDate ? scope.$eval(attrs.startDate) : '1901-01-01'), 'YYYY-MM-DD');
            if (startDateCompare && startDateCompare.isValid() && value && value.match(/\d{4}\-?\d{2}\-?\d{2}/g)) {
                var valueMoment = moment(value, 'YYYY-MM-DD');
                if (valueMoment && valueMoment.isValid() && valueMoment < startDateCompare) {
                    ctrl.$setValidity('startdate', false);
                    ctrl.$error['startdate'] = true;
                    return undefined;
                }
            }
            ctrl.$setValidity('startdate', true);
            return value;
        };
        ctrl.$parsers.unshift(compareStartDates);
    }
};
})

JSFiddle: http://jsfiddle.net/2ug4X/

Look at the fiddle above and do the following:

1) enter "A" in the text box, the pattern error triggers. 2) click the "CLICK ME" text, which updates teh value of the model on the scope, notice the error clears 3) enter "1800-01-01" in the text box, the date restriction error triggers 4) enter "2000-01-01" in the text box which is a valid date, should clear the startdate error but it doesn't. Any idea why this is happening?

I'd expect updating the ng-model bound variable like so

scope.sample.open_date = '2000-01-01';

would clear the error on the input element like the pattern error clears.

1 Answer 1

2

Found this after searching more on Stack: AngularJS custom validation not firing when changing the model programatically

it seems my error was not also pushing the compare function to the ctrl.$formatters like so:

ctrl.$formatters.unshift(compareStartDates);

this did the trick!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.