简体   繁体   English

使用自定义验证器时,formBuilder.group 显示为已弃用

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

I have built my PasswordValidator as follows:我已经按如下方式构建了我的 PasswordValidator:

// 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 中创建了表单:

  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.验证器有效,但 formBuilder 之后的 Aufrauf 组显示为已弃用。 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具有索引类型的 FormGroup 方法在 Angular 11+ 中已弃用,现在我们需要将验证器作为配置选项提供给 formGroup

Change validator ==> validators更改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然后将返回类型ValidationErrors|null添加到 customValidator 方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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