M
M
Mariik2018-06-01 11:17:08
JavaScript
Mariik, 2018-06-01 11:17:08

How to change validation order in Angular5?

Hello.
For example: there is a reactive form in which the email input field, on which several validators have been hung. More or less like this:

Email: new FormControl('', [Validators.required, Validators.email])

The problem is that when the field is empty, both validators work at once and show their error messages. And I need such a flow:
1. The required
validator works out 2. If required has worked, then only then the email validator is already working out
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-06-01
@dmitrygavrish

You can write your own validator function, like this:

function validateInSequence(
    ...validators: ( (formControl: FormControl) => any )[]
): (formControl: FormControl) => any {
    return function (formControl: FormControl): any {
        for (let i = 0; i < validators.length; i++) {
            const validationResult = validators[i](formControl);

            if (validationResult !== null) {
                return validationResult;
            }
        }

        return null;
    };
}

And use it like this:
new FormControl('', [validateInSequence(Validators.required, Validators.email)]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question