2017-05-27 89 views
1

我有4個表單字段,我想檢查'oldpass'和'newpass'字段是否使用反應形式相同。角2反應形式自定義驗證

this.changePasswordForm = fb.group({ 
    'oldpass': ['', Validators.compose([Validators.required, Validators.minLength(6)])], 
    'newpass': ['', Validators.compose([Validators.required, Validators.minLength(6)])], 
    'confirmpass': ['', Validators.compose([Validators.required])], 
    'otp': [''] 
    },{validator: CustomValidator.matchConfirmFields('newpass', 'confirmpass')}); 

而且我能夠使用下面的代碼驗證'newpass'和'confirmpass'字段。

static matchConfirmFields(pass: string, confirmpass: string) { 
     return (group: FormGroup): {[key: string]: any} => { 
     let spass = group.controls[pass]; 
     let sconfirmpass = group.controls[confirmpass]; 

     if (spass.value !== sconfirmpass.value) { 
      return { 
      mismatchedPasswords: true 
      }; 
     } 
     } 
    } 

如何驗證 'oldpass' 和 'newpass' 域類似的方式。

+0

https://scotch.io/tutorials/how-to-implement-a-custom-validator-directive-confirm-password-in-angular-2看看這個第一 – misha130

+0

感謝misha..but如何我是否要爲「oldpass」和「newpass」調用第二個驗證器。如果我誤解了你的問題,可以請你幫助 – vishnu

回答

1

我的答案改變了FormGroup中驗證器的方式。 首先,我們將爲您的課程添加一個新的驗證器功能。 它只將抽象控件與字符串進行比較,沒有什麼特別的 有一個選項可以相等或不相等。

public confirmPasswordValidator(control: AbstractControl, compareValue: string, equal: boolean = true): null | {} { 
    if ((control.value === compareValue) === equal) { 
     return null; 
    } 
    return { 
     confirmPassword: { 
     valid: false 
     } 
    } 
    } 

現在在FormGroup我們將它添加到我們想要將它添加到使用它,並表示用它做什麼都控制的控制。

this.changePasswordForm = fb.group({ 
    'oldpass': ['', Validators.compose([Validators.required, Validators.minLength(6)])], 
    'newpass': ['', Validators.compose([Validators.required, Validators.minLength(6), 
    (control) => this.confirmPasswordValidator(control, this.changePasswordForm ? this.changePasswordForm.controls['oldpass'].value : '', false)])], 
    'confirmpass': ['', Validators.compose([Validators.required, 
    (control) => this.confirmPasswordValidator(control, this.changePasswordForm ? this.changePasswordForm.controls['newpass'].value : '') 
    ])], 
    'otp': [''] 
}); 
+0

@vishnu,隨時告訴我,我會刪除這個 – misha130

+0

偉大的Misha..its工作正常。非常感謝 – vishnu