vishnu
vishnu

Reputation: 4599

Angular 2 reactive form custom validation

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.

Upvotes: 1

Views: 137

Answers (1)

misha130
misha130

Reputation: 5706

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

Upvotes: 1

Related Questions