1

How to validate reactive input field only when one is filled?

My reactive form is:

this.form = this.fb.group({
      code: [null, [Validators.required, Validators.pattern('^[a-zA-Z]+$')]],
      dateFrom: [null, []],
      dateTo: [null, []],
      uk: [null, []]
    });

I need to validate dateTo only when dateFrom is filled.

POV
  • 11,293
  • 34
  • 107
  • 201
  • you create a customValidate over all the form or over dateTo, see (and it's only one of several examples): https://stackoverflow.com/questions/57120135/best-way-to-implement-angular-cross-field-validation/57123631#57123631 – Eliseo Jul 23 '19 at 14:36

1 Answers1

1

Use custom Validator:

in TS:

checkFirstDate(group: FormGroup) {  
  let dateFrom = group.controls.dateFrom.value;
  return dateFrom ? null : { dateFromNotExist: true }     
}


this.form = this.fb.group({
      code: [null, [Validators.required, Validators.pattern('^[a-zA-Z]+$')]],
      dateFrom: [null, []],
      dateTo: [null, []],
      uk: [null, []]
    }, {validator: this.checkFirstDate });

in HTML

   <span class="text-danger" *ngIf="form.hasError('dateFromNotExist') && (form.get('dateTo').dirty || form.get('dateTo').touched)">
    Fill Date Form first
   </span>
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
  • no , return null if the dateForm field is filled , else( if empty ) return error validattion – Ghoul Ahmed Jul 23 '19 at 15:14
  • @GhoulAhmed, if you'r using material error, and want to show an error in a "input" when the error is defined in a "form" you need use errorStateMatcher. See a discussion about this in https://stackoverflow.com/questions/56876119/both-mat-error-show-when-only-one-condition-is-true. Any way in your validator you don't take account **dateTo** ¿? – Eliseo Jul 23 '19 at 19:30
  • i produce your example without mat-error :) [demo working](https://stackblitz.com/edit/angular-sn3aa7) – Ghoul Ahmed Jul 24 '19 at 09:33