AngularJS 輸入驗證
AngularJS 表單和控件可以驗證輸入的數據。
輸入驗證
在前面的幾個章節中,你已經學到關於 AngularJS 表單和控件的知識。
AngularJS 表單和控件可以提供驗證功能,並對用戶輸入的非法數據進行警告。
![]() |
客戶端的驗證不能確保用戶輸入數據的安全,所以服務端的數據驗證也是必須的。 |
---|
應用代碼
<!DOCTYPE html>
<html>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>用戶名:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">用戶名是必須的。</span>
</span>
</p>
<p>郵箱:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">郵箱是必須的。</span>
<span ng-show="myForm.email.$error.email">非法的郵箱。</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>
</body>
</html>
<html>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>用戶名:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">用戶名是必須的。</span>
</span>
</p>
<p>郵箱:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">郵箱是必須的。</span>
<span ng-show="myForm.email.$error.email">非法的郵箱。</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>
</body>
</html>
![]() |
HTML 表單屬性 novalidate 用於禁用流覽器默認的驗證。 |
---|
實例解析
AngularJS ng-model 指令用於綁定輸入元素到模型中。
模型對象有兩個屬性: user 和 email。
我們使用了 ng-show指令, color:red 在郵件的 $dirty 或 $invalid 都為 true 時才顯示。
屬性 | 描述 |
---|---|
$dirty | 表單有填寫記錄 |
$valid | 字段內容合法的 |
$invalid | 字段內容是非法的 |
$pristine | 表單沒有填寫記錄 |