简体   繁体   中英

Angular & Typescript - Date input validation in the 'Input' field

My Angular5 program includes an input field for entering date. I am using NgbDateStruct and NgbCalendar from ng-bootstrap . Though there is a calendar, for picking the date, when the user manually enters input to the date field, it doesn't validate.

That is, in the input field allotted for entering the date, the user should not be able to enter a text or garbage data. But right now, the user is able to enter any kind of data.

To do this client-side validation, I tried using <input type = "date"> , but the input type = date is not supported in IE 11 and earlier versions.

There were several solutions available in JQuery and JavaScript. But I cannot use JQuery and JavaScript in my Angular+TypeScript program.

What is the way to validate the input field for Date such that the user will not be able to enter in the input field anything other than a valid date in Typescript ?

I tried the following workaround in TypeScript, but ended up with an error:

app.component.ts :

validateDate() {
     const regExp = /^(\d{4})\/(\d\d?)\/(\d\d?)$/;
    if (((this.fromDate).toString()).match(regExp)) {
        console.log('Valid Date');
    }
}

The error I got was:

[ts] - Property 'match' does not exist on type 'NgbDateStruct'

where this.fromDate is the date input I am receiving from the view.

HTML:

<div class = "input-group date">
    <input class = "form-control" [(ngModel)] = "fromDate" ngbDatepicker #d = "ngbDatepicker" onmousedown = "validateDate()">
</div>

Steffi, your variable fromDate is an object {year:##,month:##,day:##},

To check if is a valid date you simply ask about year,month and day.

eg In a submit you can do

submit()
{
    let validDate:boolean=this.fromDate.year && this.fromDate.month && this.fromDate.day
    let data={
       fecha:validDate?''+this.fromDate.year+'/'+this.fromDate.month+'/'+this.fromDate.day:null;
    }
 }

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