Search code examples
javascriptangulartypescriptvalidationformbuilder

Combining result (ORing) of 2 validators in Angular and using it as single validating factor


I want to get a validation result on a form field by ORing the 2 validation results

e.g.

    this.registerForm = this.formBuilder.group({
username: ['', [Validators.required,Validators.pattern(USERNAME_REGEX) || Validators.email]],
    });

Is something like this possible?

Constraints: THE USERNAME SHOULD BE EITHER AN EMAIL ADDRESS OR SHOULD BE A VALID USERNAME WHICH MATCHES TO THE PATTERN OF USERNAME'S REGEX

I want to use angular's inbuilt email validators' output and the output of a custom made regex pattern to identify whether the field is valid or not.

PS: I have refered this post -> Angular 2 combined form validation but it does not match my condition


Solution

  • You need to write your own validator function.

    private loginNameValidator = (): ValidatorFn => {
        const userNameValidator = Validators.pattern(USERNAME_REGEX);
    
        return (control: AbstractControl): ValidationErrors | null => {
            const userNameInvalid = userNameValidator(control);
            if (!userNameInvalid) {
                return null;
            }
    
            const emailInvalid = Validators.email(control);
            if (!emailInvalid) {
                return null;
            }
    
            return { loginNameInvalid: true };
        };
    };
    

    Use it

    this.registerForm = this.formBuilder.group({
        username: ['', [Validators.required, this.loginNameValidator()]],
    });