如何在用户开始在angularjs中输入(输入字段长度> 0)时检查ng-pattern?

时间:2018-05-22 09:20:46

标签: javascript angularjs angular-material

我想检查模式检查输入字段长度是否> 0我该怎么办呢。

期望

  1. 当输入字段为空时显示所需消息(已触摸)
  2. 开始输入后需要检查模式如果模式不匹配需要显示请输入有效输入,如果输入字段长度0只需要显示所需信息
  3. (function(angular) {
      'use strict';
    angular.module('ngMessagesExample', ['ngMessages']);
    })(window.angular);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-messages.js"></script>
    
    
    <div ng-app='ngMessagesExample'>
       <!-- App goes here -->
       <form name="test" novalidate ng-submit="test.$valid && submit()">
          <div layout-gt-md="row">
             <md-input-container class="md-block" flex-gt-xs>
                <label>Number</label>
                <input  required ng-model="user.number" name="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" >
                <div ng-messages="test.number.$error">
                </div>
                <div ng-messages="test.$error" ng-show="test.number.$dirty">
                   <div ng-message="required">number is required</div>
                </div>
                <span ng-show="!test.number.$valid">Please Enter Valid Input</span>
             </md-input-container>
          </div>
       </form>
    </div>

    demo

    帮帮我

1 个答案:

答案 0 :(得分:1)

我更新了HTML中的代码

<!doctype html>
<html lang="en">
<head>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-messages.js"></script>
  <script src="script.js"></script>

</head>
<body>

  <div ng-app='ngMessagesExample'>
    <!-- App goes here -->
     <form name="test" novalidate ng-submit="test.$valid && submit()">
    <div layout-gt-md="row">
   <md-input-container class="md-block" flex-gt-xs>
      <label>Number</label>
      <input  required ng-model="user.number" name="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" >
      <div ng-messages="test.number.$error">


      </div>
      <div ng-messages="test.$error" ng-show="test.number.$dirty"><div ng-message="required">number is required</div></div>

      <span ng-show="test.number.$error.pattern">Please Enter Valid Input</span>
   </md-input-container>
</div>
</form>

</div>
</body>
</html>