我有疑问如何在 Angular FormGroup 中同时对两个字段有效。我必须在 value 返回后端创建自定义 validation 我不知道如何创建它。感谢您的任何想法。
回答1
您需要创建 AsyncValidator 并将其绑定到 FormGroup,然后您将可以访问组字段并可以在一个 validation 标记中验证两个字段。有一些例子给你:
group = new FormGroup(
{
a: new FormControl(''),
b: new FormControl(''),
},
{ asyncValidators: customAsyncValidator() }
);
function customAsyncValidator(): AsyncValidatorFn {
return (group: FormGroup) => {
const a = group.get('a').value;
const b = group.get('b').value;
return of('value').pipe(
delay(500),
map((value) => (value === a || value === b ? null : { fields: true }))
);
};
}