1

I have 4 form fields and i want to check whether the 'oldpass' and 'newpass' fields are same using reactive form.

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')});   

And i am able to validate the 'newpass' and 'confirmpass' fields using the following code.

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
          };
        }
      }
    }

How do i validate 'oldpass' and 'newpass' fields similar way.

2
  • scotch.io/tutorials/… check this out first Commented May 27, 2017 at 8:16
  • thanks misha..but how do i call second validator for 'oldpass' and 'newpass'. can u please help on this Commented May 27, 2017 at 8:20

1 Answer 1

1

My answer changes the way the validators in your FormGroup. First we'll add a new validator function to your class. It only compares an abstract control to a string, nothing special There is an option for equal or is not equal.

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

Now in the FormGroup we add it to the Controls we want to add it to all controls that use it and signify what to do with it.

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': ['']
});
Sign up to request clarification or add additional context in comments.

1 Comment

@vishnu if I did misunderstand your question, feel free to tell me and I'll delete this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.