Home > Back-end >  When using a custom validator, formBuilder.group is displayed as deprecated
When using a custom validator, formBuilder.group is displayed as deprecated

Time:06-09

I have built my PasswordValidator as follows:

// Function to compare password with confirmPassword
export function ConfirmedValidator(controlName: string, matchingControlName: string) {
  return (formGroup: FormGroup) => {
    const control = formGroup.controls[controlName];
    const matchingControl = formGroup.controls[matchingControlName];
    if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
      return;
    }
    if (control.value !== matchingControl.value) {
      matchingControl.setErrors({ confirmedValidator: true });
    } else {
      matchingControl.setErrors(null);
    }
  };
}

I have created the form in ngOnInit:

  ngOnInit() {
    // Create user password form
    this.cupForm = this.formBuilder.group( {
      password: [null, Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\\w\\s]).{8,}$')],
      confirm_password: [null, Validators.required]
    }, {
      validator: ConfirmedValidator('password', 'confirm_password')
    });
  }

The validator works, but the Aufrauf group after formBuilder is shown as deprecated. How can I solve the problem? Do you have any idea?

CodePudding user response:

FormGroup method with index type is deprecated in angular 11 , Now we need to provide validators as config options to formGroup

Change validator ==> validators

this.cupForm = this.formBuilder.group( {
      password: [null, Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\\w\\s]).{8,}$')],
      confirm_password: [null, Validators.required]
    }, {
      validators: ConfirmedValidator('password', 'confirm_password')
 });

Then add return type ValidationErrors|null to customValidator method

export function ConfirmedValidator(controlName: string, matchingControlName: string) {
  return (formGroup: FormGroup):ValidationErrors|null => {
    const control = formGroup.controls[controlName];
    const matchingControl = formGroup.controls[matchingControlName];
    if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
      return;
    }
    if (control.value !== matchingControl.value) {
      matchingControl.setErrors({ confirmedValidator: true });
    } else {
      matchingControl.setErrors(null);
    }
  };
}
  • Related