首页 > 解决方案 > 在Angular 9中的两个选择上验证相同的值

问题描述

我是 Angular 的新手,它实际上是另一个程序员的代码。任何想法或将不胜感激。

我有两个带有三个选项的简单选择,我正在尝试验证它们是否选择了相同的值。

我创建了一个验证器,它检查第二个选择是否与第一个选择具有相同的值。它仅适用于第二个,但是当我更改第一个选择时,验证器不会运行或更新。

代码如下所示:

  maxTimeValidator = ( control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if ( control.value !== this.RiskForm.controls.range_min_time.value ) {
      return { differentTimeRange: true, error: true };
    }

    return {}
  }


  RiskForm: FormGroup;
  submit_error = false;
  RiskData = {
    id: [null,[]],
    range_min_time: [null, [Validators.required]],
    range_max_time: [null, [Validators.required,this.maxTimeValidator]],
  }

  ngOnInit(): void {
    // Initialice Form Data
    this.RiskForm = this.formBuilder.group(this.RiskData);
  }

我尝试创建两个验证函数/相同的问题:更改一个选择时验证器似乎没有运行或更新。

任何建议都会有所帮助,感谢您花时间提供帮助。

标签: angularvalidationangular-validation

解决方案


您需要一个适用于您的表单的验证器。与此类似:

this.registerForm = this.formBuilder.group(
  {
    firstName: ["", [Validators.required]],
    lastName: ["", [Validators.required]],
    email: ["", [Validators.required, Validators.email]],
    password: ["", [Validators.required, Validators.minLength(6)]],
    confirmPassword: ["", Validators.required]
  },
  {
    // Used custom form validator name
    validator: ComparePassword("password", "confirmPassword")
  }
);


export function ComparePassword(controlName: string, matchingControlName: string) {
      return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
          return;
        }

        if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ mustMatch: true });
        } else {
          matchingControl.setErrors(null);
        }
      };
}

推荐阅读