【问题标题】:ng-pattern only numbers in not required inputng-pattern 仅用于不需要输入的数字
【发布时间】:2017-04-03 13:07:08
【问题描述】:

我有一个不需要的输入文本,我想只对数字字符使用 ng-pattern,但是当我提交表单时,输入无效。为什么?

<input type="text" ng-model="price" format="currency" ng-pattern="/^[0-9]*$/">

在 jsfiddle 中,插入产品而不输入价格并提交:

http://jsfiddle.net/2f6qscrp/266/

ps:我不能改变输入的类型!

【问题讨论】:

  • 你的意思是你输入一个数字并提交,然后出现错误?
  • 不,我有一个包含 5 个输入的表单,只需要一个 (ng-model="productCode"),但是当我汇总价格输入时,我输入了“ng-invalid-pattern”类无法继续。
  • 由于正则表达式模式很好,问题与代码有关。如果您需要帮助,请发布(也欢迎任何指向小提琴的链接)。
  • fiddle中试过这个。它在那里工作

标签: angularjs regex


【解决方案1】:

尝试使用/^[0-9]+$/ + 符号表示接受一位或多位数字。

【讨论】:

    【解决方案2】:

    看看这是否有帮助。

    var app = angular.module('demo', []);
    
    app.controller('MainCtrl', function($scope) {
    
       $scope.price = '';
       $scope.seeResults = function() {
        console.log($scope.price);
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.20/angular.min.js"></script>
    <!DOCTYPE html>
    <html ng-app="demo">
    
      <head>
        <meta charset="utf-8" />
      </head>
    
      <body ng-controller="MainCtrl">
         <form name="form" ng-submit="seeResults()" novalidate role="form">
            Price <span ng-show="form.$submitted && form.price.$error.pattern" style="color: red;">should be an integer</span>
                <input name="price" type="text" ng-model="price" format="currency" ng-pattern="/^[0-9]*$/">      
          <button type="submit" >Submit</button>
        </form>
      </body>
    </html>

    【讨论】:

    • 查看我添加的 jsfiddle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2018-06-20
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多