1

I am using the Validators.pattern to check that the name filed in my form contains only letters. The pattern I have added is lastName:[null,[Validators.required,Validators.pattern('[A-Za-z]+')]]. But I notice that in case there is an error, the error message contains extra ^ and $. Why? The code example is at https://stackblitz.com/edit/angular-xesgxe

Add an invalid name (say 1) in Last Name filed (not First Name as I am using a different validator for it. You'll see the error The required pattern is: ^[A-Za-z]+$. Notice the extra ^ and $ in the error string while the pattern was [A-Za-z]+

Check createForm() function in signup-component.component.ts. Look for line lastName:[null,[Validators.required,Validators.pattern('[A-Za-z]+')]]

The error message comes from ShowErrorsComponent. Check 'pattern': (params) => 'The required pattern is: ' + params.requiredPattern in errorMessages in the class ShowErrorsComponent.

mruanova
  • 6,351
  • 6
  • 37
  • 55
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

1 Answers1

3

Because that's how you make a regex pattern match the entire input (^ - stands for start of line and $ for end of line).

Otherwise your pattern [A-Za-z]+ will find match in this string: 123a so the validator will say the string is valid.

EDIT: Looking over the code (https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts#L293), it seems to be possible to use the exact pattern you want, by passing a RegExp instead of a string:

Validators.pattern(/[A-Za-z]+/)

My guess is they added this behavior because the pattern attribute on the input works the same (https://www.w3schools.com/tags/att_input_pattern.asp).

See also: Should I use ^ and $ in html5 input regex pattern validation?

Andrei Tătar
  • 7,872
  • 19
  • 37
  • 1
    I get that but what confused me is that `Angular` added this by itself. Shouldn't `pattern` take the exact pattern specified? – Manu Chadha Aug 24 '18 at 09:41
  • @ManuChadha Updated my response – Andrei Tătar Aug 24 '18 at 09:46
  • Many Thanks. I notice the code. I also looked at the documentation `https://angular.io/api/forms/PatternValidator` which says that the directive `Follows pattern attribute semantics; i.e. regex must match entire Control value.` and that this directive is added when `html` code uses `pattern` attribute. It seems that by default `pattern` attribute in `html` matches against the entire value of the `input`. So to make this Directive compatibe with `html`'s behaviour, `^` and `$` are added. But this is all just my theory – Manu Chadha Aug 24 '18 at 10:00
  • This was a gotcha moment for me too. In my case, I have a list of strings supplied by the API with the pattern strings. How can I use those in the validator then (so that I don't get the starter and ender characters automatically? I see you suggest using regex instead but I have strings... – Konrad Viltersten Dec 23 '19 at 19:42