简体   繁体   中英

When using a custom validator, formBuilder.group is displayed as deprecated

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM