Home > Mobile >  Using multiple Angular Validators with OR
Using multiple Angular Validators with OR

Time:01-18

Is it possible with Angular to have multiple validators with OR instead of AND. What I mean is that by default if I have 2 validators, both need to be true to have a valid form. I would like to have only one of them to be true. I could make a custom validator, but for my use case it would be much easier if there is a way to do it so I can simply, for example, specify an option to the FormControl.

this.fb.group({
    field: ['value', [Validators.pattern("^[0-9]*$"), Validators.MaxLength(50)]]
})

In this example, I would like the second validator to be ignored if the first one is true so the result would be that if you input numbers, it does not matter that the value is shorter than 50, but if you enter something else than numbers, then you need to have at least 50 characters. In other words, I want the field to be valid if <validator A || validator B>.

CodePudding user response:

The only way seems writing a custom validator.

function orValidator(validators: ValidatorFn[]) {
    return (control: AbstractControl): {[key: string]: any} | null => {
        for (const validator of validators) {
            const error = validator(control);
            if (!error) {
                return null;
            }
        }
        return { 'or': true };
    };
}

You can use it like that.

this.fb.group({
    field: ['value', orValidator([Validators.pattern("^[0-9]*$"), 
    Validators.MaxLength(50)])]
});
  • Related