簡體   English   中英

在 Angular 中組合 2 個驗證器的結果(ORing)並將其用作單個驗證因素

[英]Combining result (ORing) of 2 validators in Angular and using it as single validating factor

我想通過 ORing 2 個驗證結果來獲取表單字段的驗證結果

例如

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

這樣的事情可能嗎?

限制條件:用戶名應該是電子郵件地址或應該是匹配用戶名正則表達式模式的有效用戶名

我想使用 angular 的內置電子郵件驗證器的輸出和自定義正則表達式模式的輸出來識別該字段是否有效。

PS:我參考了這篇文章 -> Angular 2 組合表單驗證,但它不符合我的條件

您需要編寫自己的驗證器函數。

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()]],
});

沒有內置功能可以滿足您的要求。

您必須為此實現自定義驗證器。

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()]],
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM