Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

84
Vistas
Angular2 get existing validators of a formcontrol

Lets say

surname = new FormControl('', [Validators.required, Validators.minLength(2)]);

At some point depending on the situation I may add or delete any validators on surname control.

At the end How do I know what validators exists on surname control? I couldn't find any thing in documentation nor by dumping the control into console

Something like

surname.getValidators() should return - ['required', 'minLength']
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Reading validators from a control is currently not supported

See also https://github.com/angular/angular/issues/13461

about 4 years ago · Santiago Trujillo Denunciar

0

You can display error messages like this:

onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;
    for (const field in this.formErrors) {
            // clear previous error message (if any)
            this.formErrors[field] = '';
            const control = form.get(field);
            if (control && control.dirty && !control.valid) {
            const messages = this.validationMessages[field];
            for (const key in control.errors) {
                this.formErrors[field] += messages[key] + ' ';
            }
        }
    }
}
formErrors = {
    'name': '',
    'power': ''
};
validationMessages = {
    'name': {
        'required':      'Name is required.',
        'minlength':     'Name must be at least 4 characters long.',
        'maxlength':     'Name cannot be more than 24 characters long.',
        'forbiddenName': 'Someone named "Bob" cannot be a hero.'
    },
    'power': {
        'required': 'Power is required.'
    }
};

Refer: https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive-component-template

about 4 years ago · Santiago Trujillo Denunciar

0

Günter Zöchbauer's answer is still correct in Angular 6, but there is a workaround that works well for me.

My workaround depend on two observations:

First, you can see which validations are presently failing, by looking the keys on the errors object. So if you have Validators.required and Validators.minLength specified, the errors object would look like this:

{ required: true, minlenght: { ... } }

That's good enough for a lot of use cases, when you don't really care if a validator exists but doesn't prevent form submission.

Second, it turns out Angular will create validators to match the attributes set on your input. So for standard validators, my suggestion would be to not specify the validator at all.

Do something like this instead:

<input type="text" formControlName="surname" [required]="surnameRequired">

In your form declaration:

form = this.formBuilder.group({
  surname: '',
  anotherField: ['', Validators.required],
  yetAnotherField: ['', Validators.required]
});

And then set the value of surnameRequired to add or remove the validator.

I have a working StackBlitz.

My approach doesn't work for custom validators, but the bulk of my use cases don't use those. Your mileage may vary.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda