0

I have a form group and I'm trying to validate if the end date is not < then the start date etc. But my question is how to access the specific field if the form group is not declared yet.

 dateFormGroup: this.fb.group({
      start: ['', [Validators.required, DateValidator.startDateValidator(this.dateFormGroup.value.end)]], 
//todo: how to access endDate
      end: ['', DateValidator.endDateValidator(this.dateFormGroup.value.start)], //todo: how to access startDate
    })
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56

1 Answers1

-1
import { Component }  from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'reactive-form',
  templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
  
  form: FormGroup

  constructor(private fb: FormBuilder){
    this.createForm();
  }

  createForm() {
    this.form = this.fb.group({
      dateTo: ['', Validators.required ],
      dateFrom: ['', Validators.required ]
    }, {validator: this.dateLessThan('dateFrom', 'dateTo')});
  }
  
  dateLessThan(from: string, to: string) {
    return (group: FormGroup): {[key: string]: any} => {
      let f = group.controls[from];
      let t = group.controls[to];
      if (f.value > t.value) {
        return {
          dates: "Date from should be less than Date to"
        };
      }
      return {};
    }
}
  • what is the type of the `dateLessThan` function? because the typical validator for form group is `ValidatorFn` but that takes a `control: AbstractControl` – chaimm Aug 30 '23 at 21:08