You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中如何在用户输入(输入框长度>0)时校验ng-pattern?

Solution for AngularJS Input Validation with Targeted Messaging

Got it, let's tweak your code to exactly match the validation behavior you need. Here's the polished implementation with breakdowns of how it works:

Revised HTML Code

<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'>
  <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})?$/"
        >
        <!-- Required prompt: Shows only when field is touched and empty -->
        <div ng-messages="test.number.$error" ng-show="test.number.$dirty">
          <div ng-message="required">Number is required</div>
        </div>
        <!-- Invalid format prompt: Shows only when field has content that doesn't match the pattern -->
        <span 
          ng-show="test.number.$dirty && test.number.$error.pattern && user.number?.length > 0"
        >Please Enter Valid Input</span>
      </md-input-container>
    </div>
  </form>
</div>

Key Changes & Explanations

  • Required Message Logic: We kept the ng-messages block tied directly to the input's error state, and only show it when the field is $dirty (user has clicked into or interacted with it). This ensures the "Number is required" prompt only pops up when the user has touched the input but left it blank.
  • Invalid Format Message Logic: The span's visibility now depends on three checks:
    1. test.number.$dirty: The user has interacted with the input
    2. test.number.$error.pattern: The input doesn't match your regex (invalid format)
    3. user.number?.length > 0: The input has actual content (so if the user clears invalid input, we switch back to the required prompt instead of leaving the invalid message up)

Behavior Walkthrough

  1. User clicks into the input and leaves it empty → "Number is required" appears.
  2. User types invalid content (e.g., letters, 3+ decimal places) → "Please Enter Valid Input" shows up.
  3. User clears the input after entering invalid content → Prompt switches back to "Number is required".

JS Code (No Changes Needed)

(function(angular) { 'use strict'; angular.module('ngMessagesExample', ['ngMessages']); })(window.angular);

This setup perfectly aligns with your requirements, making sure the right message is displayed for every user interaction scenario.

内容的提问来源于stack exchange,提问作者its me

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:21:02