How to force Reactiveforms to validate only after trying to send the data?

Asked

Viewed 25 times

0

I have a app simple where I did some tests with the Reactive forms of Angular, and I came across the following situation: I put a console.log in the validation function, and I realized that when trying to validate a field, every letter typed it tried to validate the field:

Validation function:

export class Validacoes {
    static ValidaCpf(controle: AbstractControl) {
        console.log('validated');
        /* código da validação de CPF */
    }
}

system logs:

Imagem com dúzias de logs pra apenas um campo

Then I saw in documentation the following sentence:

We can delay updating the form validity by Changing the updateOn Property from change (default) to submit or blur.

Which means more or less:

We can delay form validation by changing the property updateOn of change (standard) for submit or blur.

And I changed the property, leaving the creation of my form so:

this.formulario = this.formBuilder.group({
        /* campos do formulário */
    }, {
        /* outras opções */
        updateOn: 'submit'
    });

Which almost solved the problem, leaving the console like this:

console quase limpo, com apenas alguns alertas ainda

But it still bothers me those three validations before I can use the form. How I remove them?

There is a project build on Github and in the Stackblitz with slight differences, but both presenting the same problem.

1 answer

1


From what I understand the behavior is correct, because as the values of the fields are initially provided, the form needs to be validated (my understanding).

If you observe, the state of the form, you will see that this.formulario.pristine is worth true, i.e., untouched. Therefore, I believe that you do not need to worry about the validations that occur when creating the form.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.