J86
J86

Reputation: 15307

Validate <input type="number" /> with AngularJS and Pattern/RegEx

I have a input of type number, and I want to make sure it only accepts a number. I can do this fine on the Server side, but with AngularJS I can not get it to work.

Here's the code:

<input type="number" ng-pattern="/[0-9]+/" name="numOfFruits" ng-model="basket.numOfFruits" />

I suspect this has something to do with the pattern I am supplying [0-9]+ basically I only want numbers in this text box, anything that is not made up of the numbers 0 to 9, I want the input invalid.

At the moment, my input field sees this aa23423 as valid input!

Upvotes: 7

Views: 19231

Answers (4)

user3827964
user3827964

Reputation: 31

Pattern don't work for input with type="number".
You can use type="text" and than convert value to number

Upvotes: 3

Eugene Fidelin
Eugene Fidelin

Reputation: 2329

Here is regexp to validate floating point numbers, both positive and negative:

/^-?[0-9]\d*(\.\d+)?$/

Use this regexp in 'text' input, example:

<input type="text" ng-model="score" ng-pattern="/^-?[0-9]\d*(\.\d+)?$/" required/>

Upvotes: 5

yotamsha
yotamsha

Reputation: 384

Try defining your regex as a scope variable In the controller, it worked for me.

Upvotes: 0

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

You need to use anchors:

/^[0-9]+$/
  • ^: Start-of-line anchor.
  • [0-9]+ One or more numbers between 0 and 9.
  • $: End-of-line anchor.

So this matches the start of the string, then it matches the one or more digits, after that it looks for the end-of-string, so it matches a string containing only numbers and nothing else.

Otherwise, /[0-9]+/ will match only a part of aa23423, more accurately the number 23423 and thus will give you valid.

Upvotes: 12

Related Questions