smartmouse
smartmouse

Reputation: 14404

Angular2: how to apply two or more validators to the same control?

I'm creating a form with Angular2 and I created two custom validators for email address field.

The first validator checks for email validity, the second (async) validator checks if email address already exists on database. In addition I would like to add a third validator for another verification.

Here is my code:

'email': ['', [validateEmail(), thirdValidator()], asyncValidator]

The behaviour that I want is the following: Only when the first validator validates the control, the second validator should start. And only when the second validator terminates then the third validator can start its validation.

How to reach this?

Upvotes: 2

Views: 1971

Answers (1)

seidme
seidme

Reputation: 13048

Validators.compose method should do the job, example:

   let formControls = {
        'oldPassword': new FormControl({ value: ''}),
        'newPassword': new FormControl({ value: ''}, Validators.compose([customValidator1, customValidator2]), customAsyncValidator)
    };

Composed validators work simultaneously, meaning we can have multiple errors on the control at the same time (each validator attaches its own error if validation failed). If we need to have only one error on the control at a time, we can 'chain' validators by checking the status of the previous validation before performing next one. Something like this:

    let customValidator2 = (ctrl: FormControl): any => {
        if(ctrl.hasError('customValidationError1')) {
            // there is the error attached by customValidator1, 
            // skip executing customValidator2 (nullify its error)
            return null;
        }

        let isInvalid = true; // some condition...

        return isInvalid ? { customValidationError2: true } : null;
    }

This way we can accomplish 'ordering' the validators by their priority for example.

Upvotes: 3

Related Questions