7

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!

0

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

10 Comments

@Ciwan Then the problem lies somewhere else, the regular expression is perfectly OK.
Thanks I too tried your RegEx in a test just now, and it works perfect !! Why is it failing in AngularJS :/
@Ciwan Unfortunately I don't with AngularJS. I just work with regular expression.
@Ciwan what version of angular do you use?
It actually isn't a bug in AngularJS. Some browsers, on input[type=number], will change the value to '' instead of the actual value if it is not a valid Number. So Angular evaluates '' as required being invalid, not Number or your Regex.
|
5

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/>

Comments

3

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

1 Comment

If what the user inputs is considered a number (as of type="number"), then pattern will catch anything else (i.e. if you specify the length of the string, or if it can contain dots, or not). (tested on Firefox)
0

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

1 Comment

Take a look here at the way integerval is defined: sravi-kiran.blogspot.co.il/2013/02/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.