how to check ng-pattern when user start typing(inp

2019-09-02 15:17发布

I want to check pattern check if input field length > 0 how can i do this .

expectation

  1. when input field empty showing required message(touched)
  2. After start typing need to check pattern if pattern is not match need to show Please Enter Valid Input and if input field length 0 need to show only required message

(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

help me out

1条回答
Viruses.
2楼-- · 2019-09-02 15:50

i have updated the code in 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>
查看更多
登录 后发表回答