表单验证-只要求一个字段或另一个.setErrors(null)不起作用——Angular 11 &



我有一个有几个字段的表单,但其中两个有以下规则:如果您填写了字段1,则不必填写字段2,反之亦然。

所有字段都有自己的自定义验证器,但是,我不确定如何为上述字段1和字段2执行验证器,因为只需要填充其中一个。我想使用一个选择,但字段需要正确填充和屏蔽,两个字段有不同的屏蔽规则。

我有以下内容:

formNewGroup: FormGroupTypeSafe<NewGroup>;
// Currently they are all under formNewGroup
inputFieldDocument: FormControl = new FormControl(); // field 1
inputOtherFieldDocument: FormControl = new FormControl(); // field 2
inputResponsibleName: FormControl = new FormControl(); // other fields
inputResponsibleEmail: FormControl = new FormControl(); // other fields
inputUserName: FormControl = new FormControl(); // other fields
inputName: FormControl = new FormControl(); // other fields
inputActive: FormControl = new FormControl(); // other fields
invalidFieldDocument = false;
invalidOtherFieldDocument = false;
// ... another invalidFields
...
validateThisField() {
const value = this.inputFieldDocument.value;
this.invalidFieldDocument = !isValid(value);
if(!this.invalidFieldDocument) {
this.formNewGroup.controls.OtherField.markAsTouched()
if(this.formNewGroup.controls.OtherField.hasError) {
this.inputOtherField.setErrors(null)
this.formNewGroup.controls.OtherField.setErrors(null)
this.formNewGroup.controls.OtherField.updateValueAndValidity()
console.log (this.formNewGroup.controls.OtherField.status) // SAYS 'INVALID'
}
}
}
...

"其他字段";确实是"田野"的一面镜子。但是引用被交换了。

我已经通过查看这里的其他问题来解决setErrors(null),它似乎对每个人都有效,所以我不知道我在这里做错了什么。

您没有使用合适的工具来解决这里的问题。您不应该在字段级别执行此操作,而应该在表单组级别执行此操作。

您需要的是一个跨字段验证器。这是它的文档。

作为一般规则,验证器可以在表单控件的任何级别定义,因此对于表单字段、表单组或表单数组都可以。给定表单控件的验证器应该只依赖于该表单控件,而不依赖于其他表单控件。这就是设计FormGroups和FormArray的主要原因之一。

相关内容

最新更新