Angular 反应形式的动态验证

时间:2021-03-15 18:48:39

标签: angular validation angular-reactive-forms

我在 Angular 中有一个反应形式。仅当已填充 taxopenDate 时,我如何才能对 closeDate 执行必需的验证?

this.employerBasicsForm = this.fb.group({
  tax: ['', [Validators.required],
  openDate: [''],
  closeDate: [''],
});

3 个答案:

答案 0 :(得分:1)

安德鲁有些喜欢

  employerBasicsForm = new FormGroup(
    {
      tax: new FormControl(),
      openDate: new FormControl(),
      closeDate: new FormControl()
    },
    this.validationTax()
  );

  validationTax() {
    return (group: FormGroup) => {
      return group.value.openDate && group.value.closeDate && !group.value.tax
        ? { required: true }
        : null;
    };
  }

不是很复杂。对我来说,这是最好的解决方案,但我也尊重你的意见。好吧,在这种情况下,我在自己的组件中使用了一个函数,因为这个验证器永远不会在组件外使用

答案 1 :(得分:0)

编写您自己的 ValidatorFn。您可以在表单组中使用它并访问表单控件以检查其状态或在表单控件本身上使用它并通过表单控件父属性访问同级控件。

https://angular.io/api/forms/ValidatorFn

答案 2 :(得分:0)

这是答案,在这种情况下不需要自定义验证器:

在没有验证器的情况下正常制作表单:

   <td style="-webkit-text-size-adjust: 100%;-ms-text-size-adjust: 100%;mso-table-lspace: 
0pt;mso-table-rspace: 0pt;word-break: break-word;-webkit-hyphens: none;-moz-hyphens: 
none;hyphens: none;border-collapse: collapse;background-image:${heroBackground};background- 
color:green;background-repeat:no-repeat;background-size:cover;background-position: center;" 
bgcolor="green" background="${heroBackground}" valign="top"> 

<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" 
  style="mso-width-percent:1000">
<v:fill type="frame" src="${heroBackground}" color="#7C64C3" />
<v:textbox style="mso-fit-shape-to-text:true" inset="0,0,0,0">

<div>
<div style="font-size: 0;line-height: 0;margin: 0;border: 0">

<![endif]--> 

您的 this.employerBasicsForm = this.fb.group({ tax: [''], openDate: [''], closeDate: [''], }); openDate 字段都需要更改方法:

closeDate

然后在您的 <div><input type="text" formControlName="openDate" (change)="checkFields()" /></div> <div><input type="text" formControlName="closeDate" (change)="checkFields()" /></div> 方法中:

checkFields