我使用<form>
在Angular2中创建了一个注册表格,如下所示:
<form [formGroup]="RegisterForm3">
<ion-item>
<ion-label>Last Date:</ion-label>
<ion-input formControlName="LastDate" min="2016" type="date"></ion-input>
</ion-item>
<hr/>
<ion-item>
<ion-label>Next Date:</ion-label>
<!--<ion-input formControlName="NextPayDate" type="number"></ion-input>-->
<ion-datetime displayFormat="MM/DD/YYYY" formControlName="NextDate" (OnChanges)="npay()"></ion-datetime>
</ion-item>
<span style="color:red" *ngIf="!RegisterForm3.controls.NextPayDate.valid && (!RegisterForm3.controls.NextDate.dirty || submitAttempt)"> * Next day Must Be Greater Than Today's Date </span>
<hr/>
<ion-item>
<ion-label>SecondDate:</ion-label>
<!--<ion-input formControlName="SecondDate" type="number"></ion-input>-->
<ion-datetime displayFormat="MM/DD/YYYY" formControlName="SecondDate"></ion-datetime>
</ion-item>
<hr/>
<ion-item>
<ion-label>Original Date:</ion-label>
<ion-datetime displayFormat="MM/DD/YYYY" formControlName="RequestedDate"></ion-datetime>
</ion-item>
<span style="color:red" *ngIf="!RegisterForm3.controls.RequestedDate.valid && (!RegisterForm3.controls.RequestedDate.dirty || submitAttempt)"> * RequestedDate Should Be 5 days Greater Than Today's Date </span>
</form>
然后form.ts
this.RegisterForm3 = formBuilder.group({
LastDate: ['', Validators.required],
NextDate:['',NextDayValidator.isValid],
SecondDate: ['',Validators.required],
RequestedDate:['',OriginalDateValidator.isValid],
});
然后我创建了两个自定义验证器类。
import { FormControl } from '@angular/forms';
export class OriginalDateValidator {
static isValid(control: FormControl): any {
var todaydate =new Date(Date.now() + (1000 * 60 * 60 * 24 * 10))
console.log(todaydate);
let duedate=new Date(control.value);
console.log(duedate);
console.log(duedate<todaydate);
//alert(npay);
if(!duedate){
return {
"is empty": true
};
}
if(duedate<todaydate){
return {
"Day must 5day greater then todaydate": true
};
}
return null;
}
}
目前的问题是,请求的date必须是下一天或次要的。因此,我需要在我的原始效果师类中测试这种情况。只有我才能访问请求的date,在验证器中单独控制值。但是我还需要在验证器中访问Next -Date和次要。是否可以在我的验证者类中访问这些字段?有帮助吗?
您可以尝试通过引用formGroup访问其他控件:
export class OriginalDateValidator {
static isValid(control: FormControl): any {
let formGroup = control.parent;
if(formGroup) {
let secondDateControl = formGroup.get('SecondDate');
console.log(secondDateControl.value);
}