角度表单验证:比较两个字段

Fra*_*rzi 5 forms validation angular-validation angular angular-forms

在Angular 4应用程序中,如何验证表单的两个字段进行比较?

例如,假设我的表单有一个startDate和一个endDate日期字段,我想确保endDate必须大于startDate.

ama*_*mal 13

当您想要实现包含一个或多个兄弟(表单)控件的验证时,您必须在兄弟控件的级别上/上定义验证器函数.例如:

ngOnInit() {
 this.form = this.formbuilder.group({
  'startDate' = ['', [<control-specific-validations>]],
  'endDate' = ['', [<control-specific-validations>]]
 }, { validator: checkIfEndDateAfterStartDate }
 });
}
Run Code Online (Sandbox Code Playgroud)

然后在组件类的定义之外(在同一文件中),也定义函数checkIfEndDateAfterStartDate.

export function checkIfEndDateAfterStartDate (c: AbstractControl) {
 //safety check
 if (!c.get('startDate').value || !c.get('endDate').value) { return null }
 // carry out the actual date checks here for is-endDate-after-startDate
 // if valid, return null,
 // if invalid, return an error object (any arbitrary name), like, return { invalidEndDate: true }
 // make sure it always returns a 'null' for valid or non-relevant cases, and a 'non-null' object for when an error should be raised on the formGroup
}
Run Code Online (Sandbox Code Playgroud)

此验证将FormGroup通过将error-flag(此处invalidEndDate)添加true到errors对象来使其无效FormGroup.如果您希望在任何兄弟控件上设置特定错误,那么您可以formControl使用类似的方法手动设置错误标志c.get('endDate').setErrors({ invalidEndDate: true }).如果你这样做,那么请确保通过将错误设置为null这样来清除它们的有效案例c.get('endDate').setErrors(null).

这里可以看到类似验证的现场演示.

  • 是的,如果它在同一个文件中,您不必“导出”该函数。我将它声明为一个 `AbstractControl`,因为它是 `FormGroup`s(以及 `FormControl`s 和 `FormArray`s)的基类。这样做没有坏处。还可以帮助您以“打字稿”的方式使用该类中定义的所有属性。 (2认同)