Home > Enterprise >  Why is the pattern validation not working here?
Why is the pattern validation not working here?

Time:12-15

I`m receiving this error: "requiredPattern": "^/(https://)([[:alnum:]]). $/ig$", "actualValue" "https://th.bing.com/th/id/OIP.K2YpOtFQ-JED8eDsHg7pdwHaEK?w=320&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7"

This should be matched by testing on regex101 : regex 101

I`m using reactive forms.

I`ve tried this way of giving the pattern :

    imageUrl: [``, [ Validators.required, Validators.pattern('^/(https:\/\/)([[:alnum:]]). $/ig')]],

Also making a variable urlPattern :

 urlPattern = /(https:\/\/)([[:alnum:]]). /ig

And calling it like this :

    imageUrl: [``, [ Validators.required, Validators.pattern(this.urlPattern)]],

My form is validation in the html is like this :

<div *ngIf="createProductForm.get('imageUrl')?.errors?.['pattern']">
                    Image URL is invalid!
</div>

It shows up, but not accepting the pattern while it should be?

What am I doing wrong?

CodePudding user response:

JavaScript does not support POSIX bracket expressions like [[:alnum:]]

Instead you could write like [a-z\d] with the case insensitive flag /i and then match 1 or more non whitspace characters using \S

Then use /^ instead of ^/ and for a match only you can omit the capture groups.

Validators.pattern(/^https?:\/\/[a-z\d]\S $/i)
  • Related