Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js ng-pattern strange behaviour

I have been working on a form that accepts Twitter parameters such as # and @ to populate a Twitter feed.

With Angular.js I had planned to use the built in ng-pattern directive to validate the input before saving, however the validation is acting extremely strangely. It marks a "valid" string as invalid on every 2nd character of the input while typing.

Its quite hard to explain the exact behaviour so heres a Plunker.

For completeness I will add my input field with the strange ng-pattern here:

<input type="text" ng-pattern="/(^|\s)@(\w+)|(^|\s)#(\w+)/g" ng-model="foo" name="foo"/>

like image 870
chrisg Avatar asked Aug 09 '26 04:08

chrisg


1 Answers

It's because of the global matching with the g option, it works if you take it out.

Calling test or exec multiple times involves state:

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

Basically it's trying to move on to another match, but can't find one:

a = /@(\w+)$/g;
> /@(\w+)$/g
a.exec("@test")
> ["@test", "test"]
a.exec("@test")
> null
like image 194
Matt Zeunert Avatar answered Aug 11 '26 04:08

Matt Zeunert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!