2016-08-14 208 views
2

鑑於簡單的登記表:角2組驗證

this.registerForm = this.formBuilder.group({ 
    email:['', Validators.compose([ 
    Validators.required, 
    Validators.pattern('[email protected]+\..+'), 
    ]), this.validators.isTaken], 
    matchingPassword: this.formBuilder.group({ 
    password: ['', Validators.compose([ 
      Validators.required, 
      Validators.maxLength(30), 
      Validators.minLength(8) 
     ])], 
    passwordConfirmation: ['', Validators.compose([ 
      Validators.required, 
     ])] 
    }, {validator: this.validators.match}) 
}) 

我試圖驗證密碼確認匹配,所以我施加匹配驗證器,以形成組。但是現在我面臨的情況是,當字段本身顯示爲有效(帶有綠色邊框,因爲它的所有驗證器都通過了),但組驗證器不是,我需要它們顯示爲紅色。

enter image description here

所以我應該改變NG-有效手動NG-無效或有一些技巧在更好的方式來解決這一問題?

+0

爲了您的具體的例子,我把自定義matchingPasswordValidator在'passwordConfirmation'領域,因爲該領域的內容時,它匹配的密碼纔有效。對於更通用的組驗證程序,我只會針對整個組發出一般錯誤消息。 –

+0

@HarryNinh,這種方法的問題是,如果我將匹配驗證器添加到'passwordConfirmation',它只會觸發此字段的更改。我的意思是,如果您更改'password'字段以使其匹配'passwordConfirmation',則最後一個仍會標記爲無效,因爲未在該字段上運行驗證。 – SET

+0

啊,你可以訂閱'password'的'valueChanges'事件來調用'passwordConfirmationControl.updateValueandValidity()'函數。 –

回答

0

我剛剛在這裏回答了這個問題[1]。

基本上,角度並不假定你想使組中的所有字段無效,因爲該組無效。您可以在模板本身補充這些信息。

我沒有你的模板,但我可以或多或少假設你可以改變你的控件以下列方式將被無效的:

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Password" formControlName="password"> 

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Confirm password" formControlName="passwordConfirmation"> 

你可能需要調整佔位符和錯誤名稱返回由自定義驗證器匹配

[1] FormControl`s of nested FormGroup are ng-valid although FromGroup is ng-invalid