javascriptangularvalidationangular-validationangular-validator

Cross field validation doesn't work in Angular


I have two date fields in two separate components. I set validations on the effective date to validate if effective date is earlier than application date. If it's earlier than application date, error message should display.

My problem right now is: if user input application date first, and effective date second, the validation works fine. But if user change the application date after they input the effective date, the validation won't fire. In another word, the validation only fire when effective date change.

How can I make the validation on effective date fire when application date changed? I also noticed that when effectiveDate is earlier than application date, the error message display. Then I change the application date to a valid date, the error message won't go away.

I have tried to pass the application date to the effectiveDate component. However, it doesn't work as I expected.

step1.component.html is the page to call the two components. I pass the applicationDate$ into the child component as [minEffectiveDate]="applicationDate$ | async".

step1.component.html, application date is inside the app-internal-use component.

<app-internal-use formControlName="internalUse" (brokerSearchIDResult)="addBrokerToApp($event)"
    (clientSearchIDResult)="handleClientSearchResult($event)" [shouldShowBrokerSearch]="shouldShowCommissionSplitBasedOnRoles">
  </app-internal-use>
...
<div class="col-sm-5">
  <app-plan-effective-date formControlName="effectiveDate" [submitted]="submitted" [minEffectiveDate]="applicationDate$ | async"></app-plan-effective-date>
</div>

effectiveDate.component.html

<label>Effective Date</label>
<div class="input-group margin-xs-bottom-10" [ngClass]="{ 'has-error' : !this.control.valid && (control.touched || submitted) }">
    <input class="form-control" [formControl]="control" bsDatepicker required [minDate]="minEffectiveDate"
        #dpEffdate="bsDatepicker">
    <span class="input-group-addon datepicker-icon" (click)="dpEffdate.toggle()">
        <i class="fa fa-calendar"></i>
    </span>
</div>
<div class="errorMessage" *ngIf="control.hasError('dateNotLessThanSpecifiedDate') && (submitted || control.touched)">Effective
    date cannot be less than the application date</div>

effectiveDate.component.ts

...
export class PlanEffectiveDateComponent extends AbstractValueAccessor implements OnInit, Validator, OnChanges {
@Input() submitted = false;
@Input() minEffectiveDate: Date;
control: FormControl;

constructor(private validatorService: ValidatorService, private cd: ChangeDetectorRef) {
    super();
}

ngOnInit() {
    this.initializeForm();
    this.handleFormChanges();
}

ngOnChanges(changes: SimpleChanges) {
    const minEffectiveDateChange = changes['minEffectiveDate'];

    if (!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
        minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
        !!this.control) {
        this.setEffectiveDateValidator();
    }
}

initializeForm() {
    this.control = new FormControl('', this.composeEffectiveDateValidator());
}

setEffectiveDateValidator() {
    this.control.clearValidators();
    this.control.setValidators(this.composeEffectiveDateValidator());
    setTimeout(() => this.control.updateValueAndValidity({ emitEvent: false }), 0);
    this.cd.detectChanges();
}

composeEffectiveDateValidator(): ValidatorFn {
    const maxEffectiveDate = utils.currentMoment().add(6, 'month').toDate();

    return Validators.compose(
        [
            this.validatorService.dateNotGreaterThanSpecifiedDate(maxEffectiveDate),
            this.validatorService.dateNotLessThanSpecifiedDate(this.minEffectiveDate)
        ]
    );
}

handleFormChanges() {
    this.control.valueChanges.subscribe(value => {
        this.value = value;
    });
}

writeValue(value) {
    if (value) {
        this.control.setValue(value, { emitEvent: false });
    }
}

validate(control: FormControl) {
    return this.control.valid ? null : { planEffectiveDateRequired: true };
}
}

dateNotLessThanSpecifiedDate function:

  dateNotLessThanSpecifiedDate(maxDate: Date) {
return (control: FormControl): { [key: string]: any } => {
  if (!!control.value && control.value < maxDate) {
    return { 'dateNotLessThanSpecifiedDate': true };
  } else {
    return null;
  }
};
}

Any help will be appreciated!

Thanks!


Solution

  • We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.

    plan-effective-date.component.ts

    control = new FormControl('', this.buildValidator.bind(this));
    
    constructor(
    private cd: ChangeDetectorRef,
    private controlDir: NgControl,
    ) {
    super();
    this.controlDir.valueAccessor = this;
    }
    
    ngOnInit() {
    this.handleFormChanges();
    this.controlDir.control.setValidators(this.validate.bind(this));
    this.updateValidity();
    }
    
    updateValidity() {
    setTimeout(() => {
      this.control.updateValueAndValidity();
      this.controlDir.control.setValidators(this.validate.bind(this));
      this.cd.detectChanges();
    }, 0);
    }
    

    Inside the ngOnChanges, call the updateValidity()

    ngOnChanges(changes: SimpleChanges) {
    const minEffectiveDateChange = changes['minEffectiveDate'];
    const currentPlanEndDateChange = changes['currentPlanEndDate'];
    
    if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
      minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
      !!this.control) ||
      (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
        currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
        && !!this.control)) {
      this.updateValidity();
    }
    }
    

    buildValidator() method is just to set your customized validators.

    Hope this will help someone who has similar issue with me :)