13

pattern to make an input text accept only numbers between 0-9.

this is my pattern:

$scope.onlyNumbers = /[\u0030-\u0039]+/g;

for some reason, chars like '-' will be accepted even though it is not in the range i have declared.

this is my input html:

  <input style="width:40%;" type="text" name="phone" ng-minlength="10" ng-maxlength="15" ng-model="register.phone" placeholder='cell phone' ng-pattern="onlyNumbers" required title="please enter cell phone">

can someone help please?

3
  • 1
    Did you try escaping the - with a backslash?
    – Foo L
    Sep 11, 2013 at 17:00
  • @FooL OP wants to exclude the -—that's the issue. Sep 11, 2013 at 17:10
  • 1
    Is there a practical reason why you're using a unicode range instead of a literal range ([0-9] or \d)? Sep 11, 2013 at 17:10

4 Answers 4

41

To make it simpler \d = any numeric value

$scope.onlyNumbers = /^\d+$/;

Example: http://jsfiddle.net/TheSharpieOne/JPkER/1/

0
13

You need to anchor the expression to restrict the value to numbers only and I don't think you need the global modifier so you expression should become:

$scope.onlyNumbers = /^[\u0030-\u0039]+$/;

And even a better expression:

$scope.onlyNumbers = /^[0-9]+$/;
2
  • @Rantiev Can't be, but be careful as your expression matches empty string as well. Feb 2, 2016 at 17:18
  • 1
    There were bug in my code above, removed it to prevent confusion.
    – Rantiev
    Feb 3, 2016 at 9:34
4

Try this for greater than 0 numbers: $scope.onlyNumbers = /^[1-9]+[0-9]*$/
For any numbers: `$scope.onlyNumbers = /^[0-9]+$/'

0

You need to edit the regx pattern

$scope.onlyNumbers = /^[0-9]{1,7}$/;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.