我有一个角度反应形式,我要在其中验证入学日期,使其最小日期为出生日期,我如何根据交叉字段进行验证
组件ts:
ngOnInit(){
this.userForm = this.formBuilder.group({
'birthDate':[''],
'admissionDate': ['']
});
}
}
@Component({
selector: 'app-plan-admission-date',
template:
<div class="form-group">
<label>Admission Date</label>
<input type="text" [formControl]="admissionDateControl" class="form-control" />
</div>
})
export class AdmissionDateComponent {
@Input() admissionDateControl:AbstractControl;
}
HTML:
<div>
<div class="container">
<main class="col-12"><h3 class="bd-title" id="content">Cross Field Validation Date</h3>
<br>
<form [formGroup]="userForm">
<div class="form-group">
<label>Birth Date</label>
<input type="text" formControlName="birthDate" class="form-control" />
</div>
<app-plan-admission-date [admissionDateControl]="userForm.controls.admissionDate"></app-plan-admission-date>
<button [disabled]="!userForm.valid" class="btn btn-primary">Submit</button>
</form></main>
</div>
</div>
有什么方法可以使用交叉字段验证date
,而无需在angular
中进行自定义验证
Stackblitz:https://stackblitz.com/edit/cross-field-date-validation-in-angular
答案 0 :(得分:3)
您可以使用@rxweb的minDate验证来代替自定义验证功能 这是代码:
ngOnInit(){
this.userForm = this.formBuilder.group({
'birthDate':[''],
'admissionDate': ['',RxwebValidators.minDate({fieldName:"birthDate"})]
});
}
}
答案 1 :(得分:1)
您是对的,您可以通过自定义验证程序来做到这一点,它看起来应该像这样(日期验证除外):
export function DateMoreThan(controlName: string, thanControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const thanControl = formGroup.controls[thanControlName];
if (control.errors && !control.errors.mustBeMoreThan) {
return;
}
if (new Date(control.value) < new Date(thanControl.value)) {
control.setErrors({ mustBeMoreThan: true });
} else {
control.setErrors(null);
}
}
}
我们将名称为controlName
的控件与名称为thanControlName
的控件的日期进行比较。 example on stackblitz在这里工作。希望有帮助。
答案 2 :(得分:0)
如果您对控件进行验证,则可以使用父级获取formGroup
this.userForm = this.formBuilder.group({
'birthDate':['11/12/2016'],
'admissionDate': ['11/12/2016',DateMoreThan('birthDate')]
});
}
export function DateMoreThan(thanControlName: string) {
return (control: AbstractControl) => {
if (!control.parent)
return null
const formGroup=control.parent as FormGroup;
const thanControl = formGroup.controls[thanControlName];
if (thanControl)
{
const [day, month, year] = control.value.split("/")
const [day2, month2, year2] = thanControl.value.split("/")
return new Date(year2,month2-1,day2).getTime()>new Date(year,month-1,day).getTime()?
{ mustBeMoreThan: true }:null
}
}
}