每個表單及輸入控件會自動獲得以下屬性(同時作為 CSS 類):
| 屬性 | CSS 類 | 含義 |
|---|---|---|
$valid | ng-valid | 當前驗證通過 |
$invalid | ng-invalid | 當前驗證失敗 |
$pristine | ng-pristine | 用戶未交互 |
$dirty | ng-dirty | 用戶已交互 |
$touched | ng-touched | 失去焦點過(Angular 1.3+) |
$untouched | ng-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) { ... }
};
<!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>
$scope.userForm.$setPristine(); $scope.user = {};ngModel.$asyncValidators.uniqueUsername = function(val) { return $http.get('/check/' + val); } 返回 Promiseng-valid/ng-invalid 類編寫 CSS,不在 JS 中操作 styleng-model-options="{ debounce: 300 }" 減少驗證頻率AngularJS 表單驗證通過聲明式指令+自動狀態管理極大簡化了前端驗證邏輯。核心掌握點:
$valid/$invalid/$dirty/$pristine 狀態機ng-show="form.field.$error.rule" 精準顯示錯誤novalidate 禁用原生驗證,完全由 Angular 控制form.$valid 一行代碼判斷整體合法性這套機制在 Angular (2+) 中以 FormControl/FormGroup 繼承發揚,理解 AngularJS 版本是掌握現代響應式表單的基石。