PrimeNG日历表单组验证问题

时间:2017-07-21 10:40:50

标签: angular validation typescript primeng primeng-calendar

我正在尝试向表单添加验证。

discount字段不能为空且值范围必须在0到100之间,time_fromtime_to不能为空。我无法在time_fromtime_to上触发验证过程。我使用PrimeNG Calendar组件。我发现p-calendar验证对ngModule有效,但我无法找到表单组的任何解决方案。

组件(简化)

ngOnInit() {
    this.buildForm();
  }

  buildForm(): void {
    this.discountFG = this.fb.group({
      discount: new FormControl('', [Validators.required, CustomValidators.range([0, 100])]),
      time_from: new FormControl('', Validators.required),
      time_to: new FormControl('', Validators.required)
    });

    this.discountFG.valueChanges
      .subscribe(data => this.onValueChanged(data));
  }

  onValueChanged(data?: any) {
    if (!this.discountFG) { return; }
    const form = this.discountFG;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

模板(简化)

          <p-calendar formControlname="time_from" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true" required></p-calendar>

          <p-calendar formControlname="time_to" [locale]="pl" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" [minDate]="minDate" readonlyInput="true" required></p-calendar>

当前行为

验证器不会注意到是否选择了日期,因此,没有触发任何事件来捕获值更改,这意味着onValueChanged认为time_fromtime_to未被触及。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

经过一些广泛的调试后,我发现表单没有验证,因为语法错误:(,你用小写formControlName拼写n。至少,代码是你的情况因此,表单控件永远不会获得值。

我在Plunk中修复它并尝试,它开始工作。

HTML:

<form (ngSubmit)="onSubmit()" [formGroup]="discountFG" class="box-model form-support-margin">
  <p-calendar formControlName="time_from" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" (blur)="setTimeFrom($event)" readonlyInput="true">

  </p-calendar>

          <p-calendar formControlName="time_to" dateFormat="yy-mm-dd" [monthNavigator]="true" [yearNavigator]="true"
            yearRange="2010:2030" [minDate]="minDate" readonlyInput="true"></p-calendar>
  <p></p>
  <button md-raised-button color="primary" type="submit" [disabled]="!discountFG.valid">Save</button>
</form> 

Plunker Demo

相关问题