Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-pattern for only numbers will accept chars like '-' in angular.js

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?

like image 812
lobengula3rd Avatar asked Sep 11 '13 16:09

lobengula3rd


People also ask

What is Ng pattern in AngularJS?

The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.

What is ng in Angular?

The ng-app directive defines the root element of an AngularJS application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.


2 Answers

To make it simpler \d = any numeric value

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

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

like image 160
TheSharpieOne Avatar answered Oct 01 '22 15:10

TheSharpieOne


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]+$/;
like image 25
Ibrahim Najjar Avatar answered Oct 01 '22 15:10

Ibrahim Najjar