FormGroup中的Angular7 DatePicker不会将错误值从CustomDateAdapter返回到formControl值

时间:2019-04-05 13:55:12

标签: datepicker angular7 angular-forms customvalidator

我在FormGroup中有一个DatePicker,并尝试使用CustomDateAdapter解析日期,然后使用自定义表单验证功能对其进行验证。

我在DatePicker中输入错误字符串,该值进入CustomDateAdapter的parse()方法,但是在此值未进入自定义表单验证功能后,我看到myForm.get('validFrom') .invalid是 false value (在 NULL 中)。但是在DatePicker中,我仍然看到错误字符串。

所以我的错误字符串出现在CustomDateAdapter的parse()上,但是没有出现在验证功能上。

component.ts:

const initialValue = { value: null, disabled: true };

this.myForm = this.formBuilder.group({
      id: null,
      name: initialValue,
      email: [initialValue, [Validators.email]],
      validity: this.formBuilder.group({
        validFrom: [initialValue, [CustomValidators.dateValidator]],
        validTo: [initialValue,  [CustomValidators.dateValidator]],
      }, { validator: CustomValidators.dateDifferenceValidators('validFrom', 'validTo') })
    });

component.html:

<mat-card>
 <mat-card-content>

<form [formGroup]="myForm">
<mat-form-field >
            <input
              matInput
              formControlName="name"
              [placeholder]="name"
              required
            >
            <mat-error *ngIf="myForm.get('name').invalid">
              Error in name
            </mat-error>
          </mat-form-field>
<mat-form-field>
            <input
              matInput
              formControlName="email"
              [placeholder]="email"
            >
            <mat-error *ngIf="myForm.get('email').invalid">
              Error in email
            </mat-error>
          </mat-form-field>

<div formGroupName="validity">
<mat-form-field>
              <input
                matInput
                [matDatepicker]="fromPicker"
                formControlName="validFrom"
                [placeholder]="date">
              <mat-datepicker-toggle
                matSuffix
                [for]="fromPicker"
              ></mat-datepicker-toggle>
              <mat-datepicker #fromPicker></mat-datepicker>
              <mat-error *ngIf="siteForm.get('validity.validFrom').invalid">
                Error in dateFrom
              </mat-error>
            </mat-form-field>
            <mat-form-field>

              <input
                matInput
                [matDatepicker]="toPicker"
                formControlName="validTo"
                [placeholder]="date"
              >
              <mat-datepicker-toggle
                matSuffix
                [for]="toPicker"
              ></mat-datepicker-toggle>
              <mat-datepicker #toPicker></mat-datepicker>
              <mat-error *ngIf="siteForm.get('validity.validTo').invalid">
                Error in dateTo
              </mat-error>
            </mat-form-field>
            <div *ngIf="siteForm.hasError('dateDifference', 'validity')">
              Dates are not valid
            </div>
          </div>
</form>
 </mat-card-content>
</mat-card>

CustomDateAdapter.ts:

import { MomentDateAdapter } from '@angular/material-moment-adapter';
import {  MAT_DATE_LOCALE } from '@angular/material/core';
import { Inject, Injectable, Optional } from '@angular/core';
import * as moment from 'moment';

@Injectable()
export class CustomDateAdapter extends MomentDateAdapter {

    constructor(@Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string) {
        super(dateLocale);
    }

    parse(value, parseFormat) {
        if (value && typeof value === 'string') {
            return moment.isMoment(value) && moment(value).isValid() ? moment(value, parseFormat) : null;
        }
        if (value && moment.isMoment(value)) {
            return moment(value, parseFormat).isValid() ? moment(value, parseFormat) : null;
        }
        if (value && moment.isDate(value) && !isNaN(value.valueOf())) {
            return moment(value, parseFormat);
        }

        return value ? moment(value).locale(this.locale) : null;
    }
}

dateValidator():

export function dateValidator(control: AbstractControl): ValidationErrors {
  const currentDate = control.value;

  if (!currentDate) {
    return null;
  }

  if (moment.isMoment(currentDate) && moment(currentDate, 'D.M.YYYY').isValid()) {
    return null;
  }
  if (moment.isDate(currentDate) && !isNaN(currentDate.valueOf())) {
    return null;
  }

  return { 'invalidDate': { value: control.value } };
}

请帮助我了解问题及其解决方法。

0 个答案:

没有答案