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
How to set a custom error message to a form in angular

I have the below code in my component:

 if (form.controls['minRange'].hasError('min')) {
        form.controls['minRange'].setErrors({ min: true });
 }

I am getting the message in input as 'minRange is invalid'.But I want to display the error message as 'P

'Please enter a 5 digit value'

Like .setErrors how can I set errormessage in formcontrol.Can any one please help me.Thanks.

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

0

Reactive Form in Angular allows you to have custom errors and custom validations. Below is an example:

HTML : Validate if the input is number.

<form  [formGroup]="form">
  <input formControlName="age" >
  <span *ngIf="form.controls.age.errors?.invalidNumber">   // <--- invalidNumber is the key
      Age should be a number
  </span>
</form>

Component.ts

 class TestComponent implements OnInit{
  form:FormGroup;

  ngOnInit(){
    this.createForm();
    this.listenToAgeChange();
  }

  createForm(){
    this.form = new FormGroup({
      age:new FormControl(null)
    })
  }

  listenToAgeChange(){
    this.form.controls.age.valueChanges.subscribe(age=>{
      if(isNaN(age)){
        this.form.controls.age.setErrors({invalidNumber:true})  // <--- Set invalidNumber to true 
      }else{
        this.form.controls.age.setErrors(null)
      }
    })
  }
}
over 4 years ago · Santiago Trujillo Relatório

0

2021 Answer. Don't access form control/error directly. Now there are functions to do so.

In HTML something like this in combination with required.

This is our custom error key.

loginForm.get('email')?.getError('invalid')

<span
      *ngIf="
        !loginForm.get('email')?.valid &&
        (loginForm.get('email')?.touched || loginForm.get('email')?.dirty)
      "
    >
      {{
        loginForm.get('email')?.hasError('required')
          ? 'Username Required'
          : loginForm.get('email')?.getError('invalid')
      }}

</span>

In Component when error occurs in API call

 this.loginForm.get('email')?.setErrors({ invalid: 'Invalid Username' });

'invalid' is key, it's value is our error message.

That's it!

over 4 years ago · Santiago Trujillo Relatório

0

TS:

if (form.controls['minRange'].hasError('min')) {
   form.controls['minRange'].setErrors({ incorrect: true, message: 'Please enter a 5 digit value'});   
}

html:

<ion-text color="danger">{{form.controls['minRange'].errors.message}}</ion-text>
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