Let's suppose that our form has a startDate and an endDate date fields and we want to make sure that startDate must be before endDate.

To implement validations containing one or more sibling (form) controls, we need to set the validator function to a higher level than the sibling controls.

form-example.component.ts
app / src / pages / form-example / form-example.component.ts
ngOnInit() : void
{
  this.formGroup = this.formBuilder.group(
  {
    startDate : new FormControl({
      value    : null,
      disabled : false
    }, [ Validators.required ]),
    endDate : new FormControl({
      value    : null,
      disabled : false
    }, [ Validators.required ]),
  },
  // NOTE Top level validator
  { validator : DateValidator.dateRangeValidator });
}

Then we define a custom validator in a separate file, for example date.validator.ts

date.validator.ts
app / src / shared / validators / date.validator.ts
// Angular modules
import { Injectable }       from '@angular/core';
import { AbstractControl }  from '@angular/forms';
import { ValidationErrors } from '@angular/forms';

@Injectable({
  providedIn : 'root'
})
export class DateValidator
{
  constructor() {}

  public static dateRangeValidator(control : AbstractControl) : ValidationErrors | null
  {
    // NOTE Safety check
    if (!control.get('startDate').value || !control.get('endDate').value)
      return null;

    // NOTE Compare fields
    // const mStart  = moment(control.get('startDate').value);
    // const mEnd    = moment(control.get('endDate').value);
    // const isValid = mStart.isBefore(mEnd);

    // NOTE Invalid
    if (!isValid)
      return { invalidDateRange : true };

    // NOTE Valid
    return null;
  }
}

If invalid, return an error object (any arbitrary name), like, return { invalidEndDate: true }

Make sure it always returns a null for valid or non-relevant cases, and a 'non-null' object for when an error should be raised on the formGroup

To display the error in our view, we use the invalidDateRange key returned by our validator.

form-example.component.ts
app / src / pages / form-example / form-example.component.html
<div *ngIf="formGroup.hasError('invalidDateRange')">
  Start date is not before the end date
</div>

JS libs #1 : Youtube

This week JS libs makes you discover Youtube like plugins for your website

© Copyright 2015 - 2022 Studio Centurio