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.

tt9
  • 4,612
  • 4
  • 40
  • 58
  • Here's a lightweight regex reference: http://www.regexpal.com/ (click on "flags", there's a regex flag to ignore case) and here is a gigantic one: http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean (ignore case is under **modifiers**). – silentsod Dec 14 '16 at 18:15
  • Build a [custom validator](http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html). – Wiktor Stribiżew Dec 14 '16 at 19:31

1 Answers1

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

    });
tt9
  • 4,612
  • 4
  • 40
  • 58
  • telling your form to reset() causes this error 'ERROR TypeError: Cannot read property 'match' of null' – Zuriel Jun 01 '17 at 19:06
  • 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 } }; – Zuriel Jun 01 '17 at 20:32