0

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

1 Answer 1

2

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)])]
});
Sign up to request clarification or add additional context in comments.

1 Comment

This kind of validator is not exactly what I was looking for, but it's a very clever and clean way to implement it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.