簡體   English   中英

Angular 中自定義驗證器的問題

[英]Problems with the custom validator in Angular

我知道這個問題已經在許多其他帖子中提出過,但在所有建議的解決方案中我找不到能為我解決問題的解決方案。

我正在嘗試創建一個驗證器來檢查輸入的確認密碼是否與密碼相同。

這是我的構建表單代碼:

    this.form = new FormGroup({
      name: new FormControl('', [Validators.required]),
      surname : new FormControl('', [Validators.required]),
      username: new FormControl('', [Validators.required, Validators.email]),
      tempUsername: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]),
      passwordTemp: new FormControl('', [Validators.required]),
    }, { validator: this.matchingPasswords }
    );
  }

這是我的驗證器方法:

  public matchingPasswords(c: AbstractControl): ValidationErrors | null {
    const password = c.get(['passwords']);
    const confirmPassword = c.get(['passwordTemp']);

    if (password.value !== confirmPassword.value) {
      return { mismatchedPasswords: true };
    }
    return null;
  }

在構建表單的第 8 行中,出現以下錯誤:

TS2345:'{ 驗證器類型的參數:(c: AbstractControl) => ValidationErrors; }' 不可分配給 'ValidatorFn | 類型的參數驗證器[] | 抽象控制選項'。 對象字面量只能指定已知屬性,並且類型“ValidatorFn | 中不存在”“validator” 驗證器[] | 抽象控制選項'。

有任何想法嗎?

您應該使用validators而不是validator

this.form = new FormGroup({
 // fields
}, { validators: this.matchingPasswords });

也許將matchingPasswords的密碼移動到導出的實用程序 function 也更好,但這只是個人代碼偏好。

其他工作符號是:

this.form = new FormGroup({
 // fields
}, this.matchingPasswords);
this.form = new FormGroup({
 // fields
}, [this.matchingPasswords]);

使用驗證器而不是驗證器

{ validators: this.matchingPasswords }

和這個

public matchingPasswords: ValidatorFn = (c: AbstractControl): ValidationErrors | null => {
        const password = c.get('passwords');
        const confirmPassword = c.get('passwordTemp');

        if (password && confirmPassword && password.value !== confirmPassword.value) {
            return { mismatchedPasswords: true };
        }

        return null;
    };

暫無
暫無

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

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