使用ngpattern验证自然输入数字

时间:2013-11-07 03:36:41

标签: angularjs regex angularjs-validation

我使用ng-pattern="/0-9/"设置price_field不接受decimal number。但是当我输入自然数(从0到9999999)时,ng-show会被Not valid number!激活。

我哪里出错了?请帮忙。

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

3 个答案:

答案 0 :(得分:120)

问题是您的REGX模式只会匹配输入“0-9”。

为了满足您的要求(0-9999999),您应该重写您的regx模式:

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

我的例子:

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");
  }
}

这是jsFiddle demo

答案 1 :(得分:10)

这是有效的

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

答案 2 :(得分:0)

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

以下代码将有助于电话号码验证,而受尊重的指令是

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');
            }
      });
    }
  }
});