nyphur
nyphur

Reputation: 2906

Why doesn't my regex work with Validators.pattern?

I have a form that I want to only allow letters, spaces, and an apostrophe. I have a Validator with Angular:

Validators.compose([
  AppValidators.required,
  Validators.minLength(2),
  Validators.pattern('[a-zA-Z ]*'),
]))

The first problem is that if I were to do

Validators.pattern(/[a-zA-Z ]*/)

The validation wouldn't work at all.

Otherwise I've tried things like

Validators.pattern('[a-zA-Z\' ]*')
Validators.pattern(/[a-zA-Z' ]*/)
Validators.pattern('[a-zA-Z\s']*')
Validators.pattern(/[a-zA-Z\s']*/)

But the validation doesn't seem to work. According to regexr, [a-zA-Z' ] seems to be what I want, but the validation still doesn't work.

EDIT:

I've tried users Thefourthbird and Brandon's answers (and while appreciate it), it doesn't work in the sense that it's still doesn't think it's valid.

I've logged the FormControl out here: console.log(this.member.control.firstName):

{
  // ....
  errors: {
    pattern: {
      actualValue: "O'Reilly",
      requiredPattern: "/^[a-zA-Z ']+$/"
    },
  },
  pristine: false,
  status: "INVALID"
}

Upvotes: 0

Views: 860

Answers (2)

wp78de
wp78de

Reputation: 19000

I think the most straight-forward solution is to use a pattern validator instead:

<input name="firstName" ngModel pattern="[a-zA-Z' ]{2,}">

See: https://angular.io/api/forms/PatternValidator

Here are some implementation samples: https://www.concretepage.com/angular-2/angular-2-4-pattern-validation-example (formControl, ngModel, etc.)

Upvotes: 0

Brandon Taylor
Brandon Taylor

Reputation: 34593

I would recommend using a RegExp object with the pattern validator. On occasion when using strings I've seen the validator behave unexpectedly.

For the pattern itself, ^[a-zA-Z ']+$ should suffice, so:

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

should get you going. RegEx validator: https://regex101.com/r/W35zae/1

Upvotes: 1

Related Questions