将两个验证器的结果(oring)以Angular 组合,并将其用作单个验证因子

8yoxcaq7  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(209)

我想通过对2个验证结果进行oring操作来获得表单字段的验证结果
例如

this.registerForm = this.formBuilder.group({
username: ['', [Validators.required,Validators.pattern(USERNAME_REGEX) || Validators.email]],
    });

这样的事情可能吗?
约束条件:用户名应该是电子邮件地址,或者应该是与用户名的正则表达式模式匹配的有效电子邮件地址
我想使用angular的内置电子邮件验证器的输出和自定义正则表达式模式的输出来确定字段是否有效。
ps:我参考了这篇文章->angular 2组合表单验证,但它不符合我的条件

sulc1iza

sulc1iza1#

您需要编写自己的验证器函数。

private loginNameValidator = (): ValidatorFn => {
    const userNameValidator = Validators.pattern(USERNAME_REGEX);

    return (control: AbstractControl): ValidationErrors | null => {
        const userNameInvalid = userNameValidator(control);
        if (!userNameInvalid) {
            return null;
        }

        const emailInvalid = Validators.email(control);
        if (!emailInvalid) {
            return null;
        }

        return { loginNameInvalid: true };
    };
};

使用它

this.registerForm = this.formBuilder.group({
    username: ['', [Validators.required, this.loginNameValidator()]],
});
m1m5dgzv

m1m5dgzv2#

没有满足您需求的内置功能。
您必须为此实现一个自定义验证器。

public userNameOrEmailValidator(): ValidatorFn => {
  return (control: AbstractControl): ValidationErrors | null => {
    const userNameRegex = // TODO: define username regex here.
    const emailRegex = // TODO: define email regex here.
    const isValid = userNameRegex.test(control.value) || emailRegex .test(control.value);
    return !isValid? {inValidUserName: true} : null;
  };
}

可以这样称呼:

this.registerForm = this.formBuilder.group({
    username: ['', [Validators.required, userNameOrEmailValidator()]],
});

相关问题