Angular - 表单组如何将表单组参数分配给自定义验证器
Angular - form group how to assign to a custom validator a form group parameter
我有一个表单组,我正在尝试验证结束日期是否小于开始日期等。但我的问题是如果尚未声明表单组,如何访问特定字段。
dateFormGroup: this.fb.group({
start: ['', [Validators.required, DateValidator.startDateValidator(this.dateFormGroup.value.end)]],
//todo: how to access endDate
end: ['', DateValidator.endDateValidator(this.dateFormGroup.value.start)], //todo: how to access startDate
})
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'reactive-form',
templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
form: FormGroup
constructor(private fb: FormBuilder){
this.createForm();
}
createForm() {
this.form = this.fb.group({
dateTo: ['', Validators.required ],
dateFrom: ['', Validators.required ]
}, {validator: this.dateLessThan('dateFrom', 'dateTo')});
}
dateLessThan(from: string, to: string) {
return (group: FormGroup): {[key: string]: any} => {
let f = group.controls[from];
let t = group.controls[to];
if (f.value > t.value) {
return {
dates: "Date from should be less than Date to"
};
}
return {};
}
}
我有一个表单组,我正在尝试验证结束日期是否小于开始日期等。但我的问题是如果尚未声明表单组,如何访问特定字段。
dateFormGroup: this.fb.group({
start: ['', [Validators.required, DateValidator.startDateValidator(this.dateFormGroup.value.end)]],
//todo: how to access endDate
end: ['', DateValidator.endDateValidator(this.dateFormGroup.value.start)], //todo: how to access startDate
})
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'reactive-form',
templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
form: FormGroup
constructor(private fb: FormBuilder){
this.createForm();
}
createForm() {
this.form = this.fb.group({
dateTo: ['', Validators.required ],
dateFrom: ['', Validators.required ]
}, {validator: this.dateLessThan('dateFrom', 'dateTo')});
}
dateLessThan(from: string, to: string) {
return (group: FormGroup): {[key: string]: any} => {
let f = group.controls[from];
let t = group.controls[to];
if (f.value > t.value) {
return {
dates: "Date from should be less than Date to"
};
}
return {};
}
}