How to modify the messages of an input validation? in Angular

0

I take this as an example:

The html

<div class="md-form">
  <input mdbInputDirective type="text" id="nombre" class="form-control" formControlName="nombre">
  <label for="nombre">Nombre</label>
</div>

The ts :

this.crearForm = this.formBuilder.group({
  nombre: new FormControl('', [
    Validators.required,
    Validators.minLength(4),
  ]),
});

As you can see it has 2 validations :

1- when required, this sends the msj: wrong

2- when it requires at least 4 characters, it also sends the msj: wrong

When everything is correct send the msj success .

How can I modify each of the messages?

That is:

1- when required, send the msj: Required field

2- when it requires at least 4 characters, it also sends the msj: Minimum 4 characters

When everything is correct send the msg Correct .

    
asked by Pablo Contreras 26.09.2018 в 22:53
source

2 answers

1

You can create a service with a function that you can use to know if the value of each field of the form is valid and return the corresponding error message

  

Create a validator.service.ts

service
import { Injectable} from '@angular/core';
import { FormGroup} from '@angular/forms';
@Injectable()
export class ValidatorService {

    public errorMessage: string;
    /**
     * @summary Usada para saber si un campo es valido o no
     * @param _field FormControlName ==> campo a validar
     * @param _form FormGroup ==> Formulario al que pertenece el campo a validar
     * @return boolean => true: válido | false = inválido
     */
    public isValid(_field: string, _form: FormGroup): boolean {
        if (_form.get(_field).invalid && _form.get(_field).touched) {
            if (_form.get(_field).errors.required) {
                this.errorMessage = "Campo requerido";
                return false;
            }
            if (_form.get(_field).errors.minlength) {
                this.errorMessage = "Mínimo" + _form.get(_field).errors.minlength.requiredLength + " caracteres";
                return false;
            }
        }
        return true;
    }
}
  

In your module:

  • Import the service
  • Add it to providers
  • import { ValidatorService } from './_services/validator.service.ts';

    providers: [ValidatorServicice]

      

    In your component:

  • Import the service
  • Inject the service into the constructor method
  • import { ValidatorService } from '../../../../_services/validator.service.ts';

    constructor(public _validator: ValidatorService) {}

      

    In your view:

    <form [formGroup]="fgTest">
        <div class="md-form">
            <input mdbInputDirective type="text" id="nombre" class="form-control" formControlName="nombre">
                <div *ngIf="!_validator.isValid('nombre', fgTest)">
                    <span style="color: #f4516c;">
                        {{ _validator.errorMessage }}
                    </span>
            </div>
            <label for="nombre">Nombre</label>
        </div>
    </form>
    

    It should be noted that in this way it was implemented only to show an error message, the first error message it finds.

    Or the other option is to view part of the validations made by the isValid function and replicate it for each element of your form.

        
    answered by 01.10.2018 / 01:44
    source
    3

    According to link , you can differentiate messages in the view according to the error

     <div *ngIf="nombre.errors.required">
        Nombre requerido.
     </div>
     <div *ngIf="nombre.errors.minlength">
        Nombre debe tener al menos 4 caracteres.
     </div>
    
        
    answered by 26.09.2018 в 23:07