我使用<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;
}
}
目前问题是,RequestedDate必须是NextDate或SecondDate。所以,我需要在我的OriginalDateValidators类中测试这个条件。只有我能够访问RequestedDate,仅在我的验证器中控制值。但我需要在我的验证器中访问NextDate和SecondDate。是否可以访问验证员课程中的那些字段?有什么帮助吗?
答案 0 :(得分:3)
您可以尝试通过引用formGroup来访问其他控件:
export class OriginalDateValidator {
static isValid(control: FormControl): any {
let formGroup = control.parent;
if(formGroup) {
let secondDateControl = formGroup.get('SecondDate');
console.log(secondDateControl.value);
}