0

I must be missing something:

<input
                  formControlName="endDate"
                  type="date"
                  id="endDate"
                  class="form-control"
                  (change)="onDateChange()"
                  required
                />
                <div *ngIf = "timesheetForm.get('endDate').errors?.invalidEndDate">
                <small class="text-danger"> TTTT</small></div>

And the .ts

  this.timesheetForm = this.fb.group({
      endDate: ["", DateValidators.invalidEndDate],
   }, {
     validator: DateValidators.invalidEndDate
   });

    const endDateControl = this.timesheetForm.get('endDate');

    endDateControl.valueChanges.subscribe((value) => {
        if (value) {
        this.timesheetForm.get('endDate').setValidators([DateValidators.invalidEndDate]);
      } else {
        this.timesheetForm.get('endDate').clearValidators();
      }
    });

And here's my custom validator

export class DateValidators {

    static invalidEndDate(formGroup: FormGroup): ValidationErrors | null  {
        let startDateTimestamp: number;
        let endDateTimestamp: number;
        for (const controlName in formGroup.controls) {
            if (controlName.indexOf("startDate") !== -1) {
                startDateTimestamp = Date.parse(formGroup.controls[controlName].value);
            }
            if (controlName.indexOf("endDate") !== -1) {
                endDateTimestamp = Date.parse(formGroup.controls[controlName].value);
            }
        }
        return (endDateTimestamp < startDateTimestamp) ? { invalidEndDate : true} : null;
    }

It's returning invalidEndDate:true, so the validation is working as expected but I am unable to display error message properly.

4
  • So TTTT is not showing..? Commented Jan 9, 2021 at 15:28
  • Yes, 'TTT' is not displayed Commented Jan 9, 2021 at 15:29
  • Hmm.. can your try to add endDateControl.updateValueAndValidity() after your if (value) condition? Commented Jan 9, 2021 at 15:33
  • I tried it before, tried it once again now, still no error message. Commented Jan 9, 2021 at 15:35

1 Answer 1

2

ValidatorFn INTERFACE

A function that receives a control and synchronously returns a map of validation errors if present, otherwise null.

based on angular.io docs:

interface ValidatorFn {
  (control: AbstractControl): ValidationErrors | null
}

You must use control not formGroup in validator constructor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.