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

86
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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