萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

AngularJS 表單驗證完整指南:內置指令、狀態管理與最佳實踐

需求場景

  • 姓名:必填
  • 用戶名:非必填,長度 3-8 位
  • 郵箱:非必填,但必須合法郵箱格式
  • 驗證不通過禁用提交,顯示錯誤提示
  • 提交成功彈窗慶祝

AngularJS 表單核心屬性與 CSS 類

每個表單及輸入控件會自動獲得以下屬性(同時作為 CSS 類):

屬性CSS 類含義
$validng-valid當前驗證通過
$invalidng-invalid當前驗證失敗
$pristineng-pristine用戶未交互
$dirtyng-dirty用戶已交互
$touchedng-touched失去焦點過(Angular 1.3+)
$untouchedng-untouched未失去焦點

訪問表單狀態

<form name="userForm">
  <input name="username" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
</form>

<!-- 模板中訪問 -->
<span ng-show="userForm.username.$error.minlength">用戶名太短</span>

<!-- 控制器中訪問 -->
$scope.submit = function() {
  if ($scope.userForm.$valid) { ... }
};

完整表單模板 (index.html)

<!DOCTYPE html>
<html ng-app="validationApp">
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/angular@1.7.9/angular.min.js"></script>
  <script src="app.js"></script>
  <style>
    .ng-invalid.ng-dirty { border-color: #dc3545; }
    .help-block { color: #dc3545; font-size: 12px; margin-top: 4px; }
  </style>
</head>
<body ng-controller="mainController">
  <div class="container">
    <div class="col-sm-8 col-sm-offset-2">
      <div class="page-header"><h1>AngularJS 表單驗證演示</h1></div>
      
      <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
        <!-- novalidate 禁用 HTML5 原生驗證 -->
        
        <!-- 姓名:必填 -->
        <div class="form-group">
          <label>姓名</label>
          <input type="text" name="name" class="form-control" ng-model="user.name" required>
          <span class="help-block" ng-show="userForm.name.$error.required && userForm.name.$dirty">
            姓名為必填項
          </span>
        </div>
        
        <!-- 用戶名:非必填,3-8 位 -->
        <div class="form-group">
          <label>用戶名</label>
          <input type="text" name="username" class="form-control" ng-model="user.username" 
                 ng-minlength="3" ng-maxlength="8">
          <span class="help-block" ng-show="userForm.username.$error.minlength && userForm.username.$dirty">
            用戶名至少 3 位
          </span>
          <span class="help-block" ng-show="userForm.username.$error.maxlength && userForm.username.$dirty">
            用戶名最多 8 位
          </span>
        </div>
        
        <!-- 郵箱:非必填,格式驗證 -->
        <div class="form-group">
          <label>郵箱</label>
          <input type="email" name="email" class="form-control" ng-model="user.email">
          <span class="help-block" ng-show="userForm.email.$error.email && userForm.email.$dirty">
            請輸入合法郵箱地址
          </span>
        </div>
        
        <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">提交</button>
      </form>
    </div>
  </div>
</body>
</html>

控制器邏輯

angular.module('validationApp', [])
  .controller('mainController', ['$scope', '$window', function($scope, $window) {
    $scope.user = {}; // 初始化模型
    
    $scope.submitForm = function(isValid) {
      if (!isValid) {
        // 標記所有字段為 dirty 觸發錯誤顯示
        angular.forEach($scope.userForm.$error, function(fieldErrors) {
          angular.forEach(fieldErrors, function(field) {
            field.$setDirty();
          });
        });
        return;
      }
      
      // 模擬提交
      $window.alert('表單驗證通過!數據:' + JSON.stringify($scope.user));
    };
  }]);

常用驗證指令速查

指令類型說明
required屬性/指令必填
ng-required="expr"指令條件必填
ng-minlength="n"指令最小長度
ng-maxlength="n"指令最大長度
ng-pattern="/regex/"指令正則匹配
type="email"屬性郵箱格式(HTML5 + Angular 雙重保障)
type="number"屬性數字格式
type="url"屬性URL 格式

自定義驗證指令

業務專用規則(如:密碼強度、手機號、身份證號)封裝為指令:

angular.module('validationApp')
  .directive('chinesePhone', function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ngModel) {
        var PHONE_REG = /^1[3-9]\d{9}$/;
        ngModel.$validators.chinesePhone = function(modelValue, viewValue) {
          var value = modelValue || viewValue;
          return !value || PHONE_REG.test(value); // 空值視為通過(配合 required 使用)
        };
      }
    };
  });

// 使用
<input name="phone" ng-model="user.phone" chinese-phone required>
<span ng-show="userForm.phone.$error.chinesePhone">手機號格式不正確</span>

表單狀態管理最佳實踐

  1. 提交時標記所有字段 $dirty:確保未交互字段的錯誤也能顯示
  2. 使用 $setPristine() 重置表單:提交成功後調用 $scope.userForm.$setPristine(); $scope.user = {};
  3. 異步驗證:ngModel.$asyncValidators.uniqueUsername = function(val) { return $http.get('/check/' + val); } 返回 Promise
  4. 樣式隔離:利用 ng-valid/ng-invalid 類編寫 CSS,不在 JS 中操作 style
  5. 防抖輸入驗證:配合 ng-model-options="{ debounce: 300 }" 減少驗證頻率

總結

AngularJS 表單驗證通過聲明式指令+自動狀態管理極大簡化了前端驗證邏輯。核心掌握點:

  • 表單/控件的 $valid/$invalid/$dirty/$pristine 狀態機
  • ng-show="form.field.$error.rule" 精準顯示錯誤
  • novalidate 禁用原生驗證,完全由 Angular 控制
  • 自定義驗證指令複用業務規則
  • 控制器中通過 form.$valid 一行代碼判斷整體合法性

這套機制在 Angular (2+) 中以 FormControl/FormGroup 繼承發揚,理解 AngularJS 版本是掌握現代響應式表單的基石。

copyright © 萬盛學電腦網 all rights reserved