如何在角度形式比较验证字段时修复错误

时间:2018-02-28 15:56:41

标签: angular angular-reactive-forms angular-forms

我正在创建自定义验证以比较日期,并在结束日期小于开始日期时打印错误。我想我正在做的一切正确,但我收到了一个错误。 当我运行我的应用程序时,它会出现错误。该错误与我使用自定义验证功能的事实有关。但这就是看每个人都这样做的方式

我的错误

AppComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'pristine' of null
        at FormGroup.campaign_period [as validator] (app.component.ts:10)
        at FormGroup.AbstractControl._runValidator (forms.js:3378)
        at FormGroup.AbstractControl.updateValueAndValidity (forms.js:3332)
        at new FormGroup (forms.js:4268)
        at FormBuilder.group (forms.js:7812)
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.



 Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});
ngOnInit() {
    this.signupForm = this._fb.group({
          firstname   : ['', Validators.required],
          lastname    : ['', Validators.required],
          date        : ['', Validators.required],
          gender      : ['', Validators.required],
          address     : ['', Validators.required],
          email       : ['', Validators.required, Validators.pattern(this.EMAIL_REGEXP)],
           city       : ['', Validators.required],
           state      : ['', Validators.required],
           country    : ['', Validators.required],
           hobbies    : this._fb.array([this.createHobbies()]),
           campaigndateForm: this._fb.group({
             startDate: ['', Validators.required],
             endDate: ['', Validators.required]
           }, { validator: campaign_period })
    });

  }
function campaign_period(c: AbstractControl): {[key: string]: boolean} | null {
  let start_date = c.get('stateDate');
  let end_date = c.get('endDate');
  if (start_date.pristine || end_date.pristine) {
     return null;
  }
    if (end_date.value > start_date.value) {
      return null;
  }
  return { 'range': true };
}

<div class="date_field_width" >
  <mat-form-field>
    <input formControlName="startDate" matInput [matDatepicker]="startdate" placeholder="Start date">
    <mat-datepicker-toggle matSuffix [for]="startdate"></mat-datepicker-toggle>
    <mat-datepicker #startdate></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <input formControlName="endDate" matInput [matDatepicker]="enddate" placeholder="End a date">
    <mat-datepicker-toggle matSuffix [for]="enddate"></mat-datepicker-toggle>
    <mat-datepicker #enddate></mat-datepicker>
  </mat-form-field>
</div>

1 个答案:

答案 0 :(得分:0)

  let start_date = c.get('stateDate');
  let end_date = c.get('endDate');
  if (start_date.pristine || end_date.pristine) {
     return null;
  }

错误是当您访问pristinestart_date end_date时,如果start_dateend_date为空,则无法访问pristine。

在检查start_date

之前,您需要先检查end_datepristine