我有7天处于开放,关闭状态。打开和关闭参数可以具有hh:mm或单词“ Closed”。因此,每个打开和关闭字段都具有正则表达式验证,以匹配hh:mm或“ Closed”字样。另外,我正在尝试添加其他跨字段验证,以确保一天中的某个字段不会被关闭。如果两者都关闭,则可以,但不能之一。
如果我有一个验证,代码似乎可以工作,但是如果我有两个验证,它就不能工作。我尝试将示例代码放到stackblitz中。
https://stackblitz.com/angular/qvjapnglrrp
正则表达式验证
/anaconda3/bin/jupyter_mac.command: line 1: dirname: command not found
/anaconda3/bin/jupyter_mac.command: line 3: /jupyter-notebook: No such file or directory
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]
跨领域验证
validateInput(c: FormControl) {
const hourMinpattern = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
const closedPattern = /^Closed$/;
return hourMinpattern.test(c.value) || closedPattern.test(c.value)
? null
: {
validateInput: {
valid: false
}
};
}
表单生成器
mondayOpenCloseValidator(formGroup: FormGroup): ValidationErrors | null {
const open = formGroup.get("mondayOpen");
const close = formGroup.get("mondayClose");
if (
(open.value === "Closed" || close.value === "Closed") &&
open.value !== close.value
) {
close.setErrors({ badState: true });
close.markAllAsTouched();
return { badState: true };
}
close.setErrors(null);
return null;
}
答案 0 :(得分:0)
我认为您的问题出在自定义验证器上 - 在验证结束时,您会清除所有错误,包括其他验证器的错误 -
删除这一行:
close.setErrors(null);
因此生成的代码将如下所示:
ondayOpenCloseValidator(formGroup: FormGroup): ValidationErrors | null {
const open = formGroup.get("mondayOpen");
const close = formGroup.get("mondayClose");
if (
(open.value === "Closed" || close.value === "Closed") &&
open.value !== close.value
) {
close.setErrors({ badState: true });
close.markAllAsTouched();
return { badState: true };
}
return null;
}