Check natural input number with ngpattern

I use ng-pattern="/0-9/" to set price_field not accept decimal number . But when I enter a natural number (from 0 to 9999999), ng-show activated using Not valid number! .

Where am I wrong? Please, help.

 <form name="myform" data-ng-submit="create()"> <input type="number" name="price_field" data-ng-model="price" require ng-pattern="/0-9/" <span ng-show="myform.price_field.$error.pattern">Not valid number!</span> <input type="submit" class="btn"> </form> 
+47
angularjs angularjs-validation
Nov 07 '13 at 3:36
source share
3 answers

The problem is that your REGX pattern will only match "0-9".

To satisfy your requirements (0-9999999), you must rewrite your regx pattern:

 ng-pattern="/^[0-9]{1,7}$/" 

My example:

HTML:

 <div ng-app ng-controller="formCtrl"> <form name="myForm" ng-submit="onSubmit()"> <input type="number" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required> <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span> <span ng-show="myForm.price_field.$error.required">This field is required!</span> <input type="submit" value="submit"/> </form> </div> 

JS:

 function formCtrl($scope){ $scope.onSubmit = function(){ alert("form submitted"); } } 

Here is the jsFiddle demo .

+104
Nov 07 '13 at 6:34
source share

Works

 <form name="myform" ng-submit="create()"> <input type="number" name="price_field" ng-model="price" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"> <span ng-show="myform.price_field.$error.pattern">Not valid number!</span> <input type="submit" class="btn"> </form> 
+8
Nov 07 '13 at 5:45
source share
 <label>Mobile Number(*)</label> <input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone required name='strMobileNo' ng-model="formModel.strMobileNo" type="text" placeholder="Enter Mobile Number"> <span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span> 

The following code will help to verify the phone number, and the respected directive -

 app.directive('validatePhone', function() { var PHONE_REGEXP = /^[789]\d{9}$/; return { link: function(scope, elm) { elm.on("keyup",function(){ var isMatchRegex = PHONE_REGEXP.test(elm.val()); if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){ elm.removeClass('warning'); }else if(isMatchRegex == false && !elm.hasClass('warning')){ elm.addClass('warning'); } }); } } }); 
0
Dec 02 '15 at 9:49
source share



All Articles