davioooh
davioooh

Reputation: 24706

AngularJS problems evaluating regex ng-pattern

I'm using ng-pattern argument in input text to limit input to numeric values:

<input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" />

But there is a strange behavior in regex evaluation: starting and ending spaces are ignored...

So if I insert these values (for example) I get different results:

' 123 ' pattern matched

' 123 4343 ' pattern not matched

In my case white spaces are not allowed (in any position of the string).

Update I need to solve the problem also for other inputs allowing char values (i.e. email)

So how can I solve this?

Upvotes: 1

Views: 455

Answers (2)

leo
leo

Reputation: 1263

You can add ng-trim="false" to your input text:

<input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" ng-trim="false" />

Take a look here

Upvotes: 0

Fordio
Fordio

Reputation: 3830

Why not just use:

<input type="number" ng-model="numericfield" />

html5 behaviour is implemented by angular in older browsers.

Upvotes: 2

Related Questions