【发布时间】:2017-07-28 01:37:05
【问题描述】:
我正在为我的反应形式的一组输入创建一个验证器。
this.transitionForm = this.fb.group({
effectiveStartDate: [this.utils.dateToISO(startDate), Validators.compose([Validators.required, this.validateDates])],
effectiveEndDate: [(endDate ? endDate : ''), Validators.compose([Validators.required, this.validateDates])],
});
/**
* Checks to make sure the start and end date selected
* are in an acceptable format.
*
* @param formGroup
*/
validateDates(formgroup: FormGroup) {
const start = formgroup.controls["effectiveStartDate"].value;
const end = formgroup.controls["effectiveEndDate"].value;
/**
* Validation Logic
* - End date cannot come before start date
* - Start date cannot come after end date
* - Start date cannot be empty
* - End Date cannot be empty
*/
if ((end < start) || (start > end) || !start || !end) {
return { invalidDates: true };
} else {
return null;
}
}
HTML:
<div *ngIf="!transitionForm.controls['effectiveEndDate'].valid">
<p *ngIf="transitionForm.controls['effectiveEndDate'].errors.invalidDates">
Invalid End Dates
</p>
</div>
由于某种原因,例如,当我将结束日期留空时,我的错误没有出现。我觉得也许我错误地调用了验证器? Compose 是我能找到的将多个验证器链接在一起的唯一方法,但我不确定是否需要传递任何东西?
更新:
这是我现有的完整表单,从各个控件中删除了验证器。它还表明我目前为这个表单设置了一个验证器,可能是不正确的。
如何包含多个?
this.transitionForm = this.fb.group({
changeType: ['', Validators.required],
effectiveStartDate: [this.utils.dateToISO(startDate), Validators.required],
effectiveEndDate: [(endDate ? endDate : ''), Validators.required],
},
{
// Validate to make sure we selected at least one transition field
validator: (formGroup: FormGroup) => {
return this.validateFilter(formGroup);
}
});
【问题讨论】:
-
如果 startDate 输入 endDate 是强制性的吗?需要这种类型的验证吗?
标签: angular typescript angular-reactive-forms