简体   繁体   中英

Angular custom validator returning the FormControl when value is null

I have an Angular Reactive form group using a custom validator. I am using 2 date pickers and want to confirm if a user selects a date from 1 they have to select a date from the other. I am having issues doing this due to null checks. So in my testing I am just filling out the first date picker and leaving the second untouched - but this is causing strange issues. the unfilled out Form Control has a value: null but when I console log that value I am getting back the formControl

this.form = this.fb.group({
      reservationNumber: this.fb.control(null),
      reservationName: this.fb.control(null),
      dateGroup: this.fb.group(
        {
          beginDate: [this.fb.control(null)],
          endDate: [this.fb.control(null)],
        },
        { validators: checkIfEndDateAfterStartDate }
      ),
      organizationName: this.fb.control(null),
      firstName: this.fb.control(null),
      lastName: this.fb.control(null),
   
    });
  }

here is my custom Validator

export function checkIfEndDateAfterStartDate(
  c: AbstractControl
): { [key: string]: boolean } | null {
  const beginDateControl = c.get('beginDate');
  const endDateControl = c.get('endDate');

  //safety check
  if (beginDateControl?.pristine && endDateControl?.pristine) {
    return null;
  }

  **console.log(endDateControl?.value);** // this console logs the actual form control so on null checks it comes back as Valid. The form control object though in console log has the value as null

  if (
    (beginDateControl?.value && !endDateControl?.value) 
  ) {
//never hits because of above
    return { datesInvalid: true };
  }

  return null;
}

You have a mistake on the initialize form with the formBuilder

Try to change to this way.

this.form = this.fb.group({
          reservationNumber: [],
          reservationName: []
          dateGroup: this.fb.group(
            {
              beginDate: [],
              endDate: [],
            },
            { validators: checkIfEndDateAfterStartDate }
          ),
          organizationName: []
          firstName:[]
          lastName:  []
       
        });
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM