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?

Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69
lobengula3rd
  • 1,821
  • 4
  • 26
  • 39

4 Answers4

41

To make it simpler \d = any numeric value

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

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

TheSharpieOne
  • 25,646
  • 9
  • 66
  • 78
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]+$/;
Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
4

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

Tanya
  • 66
  • 2
0

You need to edit the regx pattern

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