2017-05-27 95 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