1

In Angular 2.1.0 Reactive forms, I have a form using the formBuilder group function that attempts to use the pattern validator to validate one of the fields.

this.profileForm = this.formBuilder.group({
'email': [this.profile.email, [
            Validators.pattern('^[a-z0-9A-Z_]+(\.[_a-z0-9A-Z]+)*@[a-z0-9-A-Z]+(\.[a-z0-9-A-Z]+)*(\.[a-zA-Z]{2,15})$')
        ]],
//...

As you can see I have manually added the uppercase A-Z on the groups, but I was wondering if there is a way to specify the pattern validator to ignore case. I can't seem to find any examples online, and as I can tell you can't pass in an actual RegExp object it has to be a string.

2

1 Answer 1

3

In the more recent versions of Angular, these have fixed this issue, and the Validators.pattern function accepts RegExp objects now.

For this version I simply created a custom validation class and added my own pattern function which accepts a RegExp object. Looks like this:

import { AbstractControl, ValidatorFn } from '@angular/forms';
export class CustomValidators {

    public static pattern(reg: RegExp) : ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            var value = <string>control.value;
            return value.match(reg) ? null : { 'pattern': { value } };
        }
    }
}

And the form that is referencing this validator looks like this:

    this.profileForm = this.formBuilder.group({
        'firstName': [{ value: this.profile.firstName, disabled: true }],

        //... other fields

        'email': [this.profile.email, [
            CustomValidators.pattern(/^[a-z0-9_]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$/ig)
        ]],

        //...other fields

    });
Sign up to request clarification or add additional context in comments.

2 Comments

telling your form to reset() causes this error 'ERROR TypeError: Cannot read property 'match' of null'
changing this fixes it, but i guess it doesnt matter if angular 4 has pattern and regex. return value && value.match(reg) ? null : { 'pattern': { value } };

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.