0
votes

I'm trying to display an error message next to my datepicker if the user selects a to-date which is earlier than the selected from-date and opposite. This message should only show after the user clicks the submit button.

code:

 <form name="form" ng-submit="ctrl.submit(form.$valid)" novalidate>
        <div class="form-group">
            <md-datepicker name="fromDate" ng-model="ctrl.fromDate" ng-required="ctrl.toDate" md-max-date="ctrl.toDate"></md-datepicker>
        </div>
        <div ng-messages="form.fromDate.$error" ng-if="form.$submitted">
            <div ng-message="maxdate">From-date should be before to-date</div>
            <div ng-message="required">Fill in from-date</div>
        </div>

        <div class="form-group">
            <md-datepicker name="toDate" ng-model="ctrl.toDate" ng-required="ctrl.fromDate" md-min-date="ctrl.fromDate"></md-datepicker>
        </div>
        <div ng-messages="form.toDate.$error" ng-if="form.$submitted">
            <div ng-message="mindate">To-date should be after from-date</div>
            <div ng-message="required">Fill in from-date</div>
        </div>

        <button type="submit">Submit</button>
    </form>

If i select fromDate 1/1/2 and toDate 1/1/1 then click submit, only the required error message is shown. When inspecting the $error object, i see that the mindate/maxdate property is cleared when i click submit.

Im assuming this is due to md-datepicker not setting the model-value if the input-value is invalid according to rules like required, min, max etc.

Is it possible to get around this somehow?

Edit: I think the problem is that angular is using the model-values to apply form errors after clicking submit instead of the input-values.

If I enter 1/1/2 as fromDate and click submit, then enter 1/1/1 as toDate, the correct error message will show.

1
You could try using ng-model-options and set {allowInvalid:true}. No clue if it will fix your issue, just a guess. - George
Doesnt seems like allowInvalid does anything significant. Even though it did, I would be hesitant to use it as it would let the user set values like "abc123"(right?). Want to avoid handling that myself if i can. - mTv
yeah I think so. I just realised your datepickers don't have a model, you need to put ng-model on the md-datepicker elements - George
Yea, thanks. I'm working in an offline environment, so I have to manually copy the code over. Knew i would forget something:P - mTv
I've created a fiddle which is working fine, have you included ngMessages as a dependency in your app? - George

1 Answers

0
votes

It seems when form loads the toDate and fromDate is blank!! Am i right?? if toDate and fromDate is blank then please initialize the fromDate and toDate with dayBeforeDate and currentDate respectively.

Like

fromDate - 22March, 2017

toDate - 23March, 2017