使用角度进行跨字段验证



我正在尝试创建一个验证器来检查梁(船的宽度(是否大于长度。 在组件中:

this.vesselForm = this.fb.group({
  beam: [null, [
    Validators.required,
    BeamValidators.beamCannotBeGreaterThanLength,
  ]],
  length: [null, Validators.required],
});

在文件中 beam.validators.ts:

import { AbstractControl, ValidationErrors } from '@angular/forms';
export class BeamValidators {
    static beamCannotBeGreaterThanLength(control: AbstractControl): ValidationErrors | null {
      const hullLength = control.parent.controls['length'].value;
      // const hullLength = 48;
      console.log(hullLength);
      if ((control.value >= hullLength)) {
          return { beamCannotBeGreaterThanLength: true };
      } else {
          return null;
      }
  }
}

我无法弄清楚如何从验证器访问长度。 该代码编译过去的智能感知,但在浏览器中出现控制台错误:

ERROR TypeError: Cannot read property 'controls' of undefined
    at BeamValidators.beamCannotBeGreaterThanLength (beam.validators.ts:6)

程序的其余部分使用测试线工作正常//const hullLength = 48;

若要实现交叉验证,必须将验证提升到FormGroup级别。

import { Component } from '@angular/core';
import {ValidatorFn, FormGroup, Validators, FormBuilder } from '@angular/forms';
const beamValidator: ValidatorFn = (fg: FormGroup) => {
  const beam = fg.get('beam').value;
  const length = fg.get('length').value;
  return beam < length ? null : { beamError: true };
}
@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">
    <input [formControl]="form.get('beam')" type="number" />
    <input [formControl]="form.get('length')" type="number" />
  </form>
  {{ form.valid }}
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 form: FormGroup;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      beam: [null, [
        Validators.required,
      ]],
      length: [null, Validators.required],
    }, { validator: beamValidator});
  }
}

现场演示

我正在尝试将这种类型的验证包含在官方文档中。如果你认为这很合适,请考虑对这个Github问题投赞成票。

最新更新