Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.2K
Visualizações
Angular: mat-error is not working on custom validator

I am unable to properly implement mat-error style change when DatePicker end date input is less than the start date input. The button is able to recognize that the input is invalid by disabling itself, but no error style changes happens on 'end_date'.

Code:

    <mat-error *ngIf="userAddressValidations.hasError('validator')">
      End date must be greater than start date.
    </mat-error>

My goal is to show this error message when the custom validator detects the error.

This is my full sample code:

Stackblitz

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

A mat-error only work for error in controls, not for errors in formGroup.

But before change your dateCheck to return an object with property "validator", not "date"

function dateCheck(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    if (
      control.value.end_date &&  //<--check only if has value, not !==undefined
      (isNaN(control.value.end_date) ||
        control.value.end_date < control.value.start_date)
    ) {
      return { validator: true };  //<--see that it's "validator"
    }
    return null;
  };
}

Then create a customErrorMatcher

export class DateEndMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    //see the comparision
    return !!(control && (control.invalid || form.invalid) && (control.dirty || control.touched || isSubmitted));
  }
}

And declare in your .ts

endDateMatcher = new DateEndMatcher();

And use in the .html

 <input matInput [matDatepicker]="picker2" formControlName='end_date' 
        [errorStateMatcher]="endDateMatcher">

You can see in your forked stackblitz

NOTE: In the new material angular you has a range date picker

Update there' another approach that it's use SetErrors

function dateCheck(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    if (
      control.value.end_date &&
      (isNaN(control.value.end_date) ||
        control.value.end_date < control.value.start_date)
    ) {
      //indicate that setErrors
      control.get('end_date').setErrors({validator:true})
      return { validator: true };
    }
    if (control.value.end_date)
       control.get('end_date').setErrors(null) //<--put the setErrors to null
    return null;
  };
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda