简体   繁体   中英

How to validate date in Angular 5 app using datepicker?

I have the current template:

<input type="text" class="datepicker" name="my_date" placeholder="mm/dd/yyyy" #myDate="ngModel" [(ngModel)]="myDate" id="my_date">
<div class="error_message" *ngIf="myDate.errors?.invalidDate">
    Please enter valid date
</div>

I have the following code in onInit:

setTimeout(function () {
      $('.datepicker').datepicker({
        autoclose: true,
        dateFormat: 'MM/dd/yyyy'
      }).on('hide', function(e) {
          $('.datepicker').blur();
      });    
    }, 10);

And when saving the company I have the validation logic:

if (validateDate(this.myDate) == false) {     
        myFormDirective.form.controls['my_date'].setErrors({'invalidDate': true});
    }   

The problem is that when the date is invalid datepicker put today date instead when onblur. To explain the question I'll give 2 scenarios: 1. 03/10/1800 is not valid date (less than 1900) and when onblur fired, the error is shown correctly. 2. 01/32/2002 is not valid date but, in this case datepicker instead select another valid date in year 2002 02/01/2002 instead of showing error.

Any idea how tom make sure validation happening on blur ?

I'd strongly recommend that you drop the jQuery datepicker for a more modern Angular datepicker component. There are many potential options available. The problem is that the way the two frameworks approaches DOM manipulation are inherently at odds. jQuery modifies the DOM after its been created, while Angular creates the DOM such that it will always be in the correct state, dependent on your model. While you can still use them together, it's probably not the best design approach.

In this specific case, if you used, for example, ngx Bootstrap's Date-picker component , you can easily attach an on Change event handler.

 import { Component } from '@angular/core'; @Component({ selector: 'demo-datepicker-value-change-event', templateUrl: './value-change-event.html' }) export class DemoDatepickerValueChangeEventComponent { data: Date; showWarning: boolean = false; onValueChange(value: Date): void { if(validateDatepicker(value)) showWarning = false; else showWarning = true; } validateDatepicker(value: Date){ let isValid = false; //Custom validation here... return isValid; } } 
 <div class="row"> <div class="col-xs-12 col-12 col-sm-6 col-md-4 form-group"> <input class="form-control" placeholder="Datepicker" bsDatepicker (bsValueChange)="onValueChange($event)"> </div> <div *ngIf="showWarning">Enter a valid date</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM