2016-10-10 41 views
0

我已經嘗試在我的表單中添加多個角度驗證器參數[即Validators.minLength(8)和Validators.maxLength(12)],我似乎無法得到它工作......這些參數被附加到下面代碼中的(password和passwordc)實例。請幫忙嗎?我如何在Angular 2表單中添加更多的Validator參數

export class signupComponent { 
     signupform: FormGroup; 
     constructor(public fb: FormBuilder) { 
      this.signupform = this.fb.group({ 
       firstname: ['', Validators.required], 
       lastname: ['', Validators.required], 
       account: this.fb.group({ 
        email: ['', Validators.required], 
        **password: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')], 
        passwordc: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')], 
       }, { validator: passwordMatcher }),** 
       shortbio: ['', Validators.required] 
      }); 

     } 
    } 

回答

1

要支持多個驗證器,您必須使用接受驗證器數組的Validator.compose([])方法。你的情況:

password: ['', Validators.compose([Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')])] 
+2

以前是這樣,但不再是(IIRC:RC3或RC4)。現在,您可以簡單地傳遞一個驗證器數組 - 您不再需要'Validators.compose()'。然而,'Validator.compose()'*仍然可以被使用,所以我認爲你的答案會解決這個問題。 – BlueM

-1
password: ['', [Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')]] 

這應該爲你做的工作。

+0

這與其他答案**非常相似。我認爲它應該是對另一個答案的評論,而不是一個單獨的答案。 – MSeifert

+0

相似但不相同。我已經省略了「撰寫」。沒有必要。我簡化了它。 – Mano

+0

是的,這也是[已經提到](http://stackoverflow.com/questions/39965847/how-do-i-add-more-that-one-validator-argument-in-angular-2-form/42634393 ?noredirect = 1#comment67223310_39966100),對吧? – MSeifert

相關問題