2017-05-27 19 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 
      }; 
     } 
     } 
    } 

どのようにi 'は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'の2番目のバリデータを呼び出しますか?私はあなたの質問を誤解した場合、私に教えてくださいと私に教えてくださいこれを削除します – 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

関連する問題