mTv
mTv

Reputation: 1366

Cant detect <form>.$error.mindate when <form>.$submitted

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.

Upvotes: 0

Views: 310

Answers (1)

Anurag Dadheech
Anurag Dadheech

Reputation: 629

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

Upvotes: 0

Related Questions