Angular 2 : Validators.pattern() not working

I am trying to validate input type="text" using a pattern. I want text only.

Component :

 this.from = this.fb.group({
  name: ['',[Validators.required,Validators.pattern('/^[a-zA-Z]+$/')]],

});

Html :

<input type="text" formControlName="name"/> // omitting other html template like from tag.

The above pattern validation is not working for me. It always returns an invalid state.


Solution 1:

Pass pattern as string, without / which are the delimiters for regex

Validators.pattern('^[a-zA-Z]+$')

Solution 2:

Remember to not do this:

Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}")

The gotcha is that you need a double backslash before the s to defeat string escape thus:

Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\\s?[0-9][A-Z]{2}")