Angular 2验证一个日期输入等于或等于另一个日期输入

时间:2016-11-04 14:51:44

标签: twitter-bootstrap angular typescript bootstrap-datepicker ng-bootstrap

我有两个输入,由两个Angular 2 Bootstrap datepickers填充。如果FormGroupstartDate之后(不在之前或之前),我希望我的按钮与endDate相对应。现在,如果我选择的startDate晚于endDate,则提交按钮会保持启用状态。但是,如果我再单击第二个日历按钮以弹出第二个datepicker,则提交按钮将被禁用(我实际上不必选择endDate)。我使用控制台进行了检查,startDateendDateerror都在更改并在正确的时间更改为正确的值而没有错误,它只是禁用已关闭"计时"。

的提交按钮
<form class="form-inline">
<div>
<div class="form-group" [ngClass]="{'has-error':!secondForm.controls['startDate'].valid && secondForm.controls['startDate'].touched}">
  <label>Start Date:</label>
  <input style="width:250px" [value]="getDate('start')" class="form-control" type="text" [formControl]="secondForm.controls['startDate']">
</div>
<div style="display:inline-block">
  <ngb-datepicker id="special" *ngIf="startCheck;" [(ngModel)]="startDate" (ngModelChange)="showDatePick(0)" [ngModelOptions]="{standalone: true}"></ngb-datepicker>
</div>
<button type="button" class="btn icon-calendar" (click)="showDatePick(0)"></button>
<div class="form-group" [ngClass]="{'has-error':!secondForm.controls['endDate'].valid && secondForm.controls['endDate'].touched}">
  <label>End Date:</label>
  <input style="width:250px" [value]="getDate('end')" class="form-control" type="text" [formControl]="secondForm.controls['endDate']">
</div>
<div style="display:inline-block">
  <ngb-datepicker id="special" *ngIf="endCheck;" [(ngModel)]="endDate" (ngModelChange)="showDatePick(1)" [ngModelOptions]="{standalone: true}"></ngb-datepicker>
</div>
<button type="button" class="btn icon-calendar" (click)="showDatePick(1)"></button>
<button type="submit" class="btn icon-search" [disabled]="!secondForm.valid || error==true"></button>
</div>
</form>

相应的打字稿:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';
import {DatePipe} from "@angular/common";
import * as moment from 'moment';

@Component({
selector: 'calendar-pick',
styleUrls: ['../app.component.css'],
templateUrl: './calendarpick.component.html',
providers: [DatePipe]
})

export class CalendarPickComponent {
public error: boolean = false;
public dt: NgbDateStruct;
public dt2: NgbDateStruct;
public startCheck: boolean = false;
public endCheck: boolean = false;
secondForm : FormGroup;

public constructor(fb: FormBuilder, private datePipe: DatePipe) {
this.secondForm = fb.group({
  'startDate' : [this.dt, Validators.required],
  'endDate' : [this.dt2, Validators.required]
})
this.secondForm.valueChanges.subscribe( (form: any) => {
    console.log('form changed to:', form);
  }
);
}

public getDate(dateName: string) {
let workingDateName = dateName + 'Date';
let timestamp = this[workingDateName] != null ? new Date(this[workingDateName].year, this[workingDateName].month-1, this[workingDateName].day).getTime() : new Date().getTime();
this.secondForm.controls[dateName + 'Date'].setValue(this.datePipe.transform(timestamp, 'longDate'));
}

public showDatePick(selector):void {
if(selector === 0) {
  this.startCheck = !this.startCheck
} else {
  this.endCheck = !this.endCheck;
}
this.periodValidator(this.secondForm);
}

periodValidator(formGroup:FormGroup) {
let s = new Date(formGroup.value.startDate);
let e = new Date(formGroup.value.endDate);
let stDt = moment(s);
let endDt = moment(e);
if (stDt > endDt) {
  this.error = true;
}else {
  this.error = false;
}
}

}

2 个答案:

答案 0 :(得分:2)

您可以定义自定义验证器并将其作为整体分配给表单组,如下所示:

endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp, endDateTimestamp;
    for(var controlName in formGroup.controls) {
      if(controlName.indexOf("startDate") !== -1) {
        startDateTimestamp = Date.parse(formGroup.controls[controlName].value);
      }
      if(controlName.indexOf("endDate") !== -1) {
        endDateTimestamp = Date.parse(formGroup.controls[controlName].value);
      }
    }
    return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
  }

这将检查控件的时间戳,如果无效则返回 ,如果有效则返回null。

this.secondForm = fb.group({
    'startDate' : ['', Validators.required],
    'endDate'  : ['', Validators.required]
  },
  {validator: this.endDateAfterOrEqualValidator});

我想如果您不打算添加任何其他控件,您可以对时间戳的分配进行硬编码,而不是检查所需值的控件。

Plunker:http://plnkr.co/edit/Yow6DMd2soBXwJ2oGOFu?p=preview

答案 1 :(得分:0)

对于我的日期选择器组件,我已将此代码用作验证器。

if(this.dateFrom && this.dateTo) {

    var d1 = Date.parse(this.dateTo);
    var d2 = Date.parse(this.dateFrom);

       if (d1 > d2) {
           this.error = true;
       }
}

如果是标准的javascript或时刻日期格式,这应该适用于你的。同样在 if 语句中,您可以设置一个error = true的变量,然后这将触发错误消息,如下所示。

<button [disabled]="error"></button>

希望这个掠夺者有所帮助:plunker example