如何编写多种形式的验证器函数以角形式的一种形式(反应形式)?

时间:2018-09-15 16:43:27

标签: angular angular5 angular6 angular-forms

我正在使用反应式表单

我的表单就是这样

this.fb.group({
            percentAllocation: [''],
            constantPercent: [''],
            allocStartDate: [''],
            allocEndDate: [''],
                   },  { validator: this.percentageValidator('percentAllocation', 'constantPercent'))

我需要两种类型的验证

1)allocStartDate < allocEndDate

2)percentAllocation > constantPercent

以上两个验证是相互依赖两个窗体控件的。我尝试这样写验证

 percentageValidator(rowPercentage, constantPercent) {
    return (group: FormGroup): { [key: string]: any } => {
        let r = group.controls[rowPercentage];
        let c = group.controls[constantPercent]
        if (r.value > c.value) {
            return {
                percentage: true
            };
        }
        return {};
    }
}

dateLessThan(from: string, to: string) {

    console.log(from, to)
    return (group: FormGroup): { [key: string]: any } => {
        let f = group.controls[from];
        let t = group.controls[to];
        if (f.value > t.value) {
            return {
                dates: true
            };
        }
        return {};
    }
}

请帮助我输入多个进行验证,并且错误消息应该仅通过ts表格

1 个答案:

答案 0 :(得分:1)

当存在更简单,更好的解决方案时,为什么要选择复杂的解决方案。

我更喜欢以下方法来比较“自定义验证器”中的两个控件

组件

  constructor(private fb: FormBuilder) { }
  public myForm: FormGroup;
  ngOnInit() {
    this.myForm = new FormGroup({
      percentAllocation: new FormControl('21'),
      constantPercent: new FormControl('26', this.percentageValidator),
      allocStartDate: new FormControl('', this.dateLessThan),
      allocEndDate: new FormControl(''),
    })
    this.myForm.statusChanges.subscribe(val => console.log(val))
  }

  percentageValidator(control: FormControl): { [key: string]: boolean } {
    if (control.parent) {
      let c = Number(control.parent.value['percentAllocation']);
      let r = Number(control.value);
      if (r > c) {
        return {
          'percentage': true
        };
      }
      else return null;
    }
  }

  dateLessThan(control: FormControl): { [key: string]: boolean } {
    if (control.parent) {
      let f = control.parent.value['allocEndDate']
      let t = control.value
      if (new Date(f) < new Date(t)) {
        return {
          'dates': true
        };
      }
      else
        return null;
 }
  }
}

HTML

<div class="container">
<form [formGroup]="myForm">
    <div class="form-group">
       <label for="peralloc">percentAllocation</label>
  <input type="text" 
   class="form-control" formControlName="percentAllocation">
    </div>
    <div class="form-group">
       <label for="conper">constantPercent</label>
  <input type="text"  class="form-control" 
  formControlName="constantPercent">
    </div>
    <div class="form-group">
      <label for="allocstart">allocStartDate</label>
  <input type="date"  class="form-control" 
  formControlName="allocStartDate">
    </div>
    <div class="form-group">
        <label for="allocEnd">allocEndDate</label>
 <input  class="form-control" type="date" 
 formControlName="allocEndDate">
    </div>
 <div *ngIf="myForm.get('constantPercent').errors && myForm?.get('constantPercent')?.errors?.percentage">
     percentAllocation should be greater than constantPercent
  </div>
  <div *ngIf="myForm.get('allocStartDate').errors && myForm?.get('allocStartDate')?.errors?.date ">
     end Date should be greater than start Date
  </div>
</form>
</div>

增加了引导程序位;)

Live Demo