AngularJS的表單驗證大致有兩種,一種是手動驗證,一種是自動驗證。
一、手動驗證
所謂手動驗證是通過AngularJS表單的屬性來驗證。而成為AngularJS表單必須滿足兩個條件:
1、給form元素加上novalidate="novalidate";
2、給form元素加上name="theForm",如下:
<!DOCTYPE html><html lang="en" ng-app="myApp1"><head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css"/> <link rel="stylesheet" href="../css/main.css"/></head><body><nav > <div class="container"> <div class="navbar-header"> <a href="/" class="navbar-brand">Form Submitting</a> </div> </div></nav> <div class="container main-content" ng-controller="myCtrl1"> <!--novalidate讓表單不要使用html驗證--> <!--theForm變成scope的一個欄位--> <form ng-submit="onSubmit(theForm.$valid)" novalidate="novalidate" name="theForm"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" ng-model="formModel.name"/> </div> <div class="form-group" ng-class="{ 'has-error': !theForm.email.$valid && (!theForm.$pristine || theForm.$submitted), 'has-success': theForm.email.$valid && (!theForm.$pristine || theForm.$submitted) }"> <label for="email">Email</label> <input type="email" class="form-control" id="email" ng-model="formModel.email" required="required" name="email"/> <p class="help-block" ng-show="theForm.email.$error.required && (!theForm.$pristine || theForm.$submitted)">必填</p> <p class="help-block" ng-show="theForm.email.$error.email && (!theForm.$pristine || theForm.$submitted)">email格式不正確</p> </div> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" ng-model="formModel.username"/> </div> <div class="form-group"> <label for="age">Age</label> <input type="number" class="form-control" id="age" ng-model="formModel.age"/> </div> <div class="form-group"> <label for="sex">Sex</label> <select name="sex" id="sex" class="form-control" ng-model="formModel.sex"> <option value="">Please choose</option> <option value="male">Mail</option> <option value="femail">Femail</option> </select> </div> <div class="form-group"> <label for="password">Password</label> <input type="text" class="form-control" id="password" ng-model="formModel.password"/> </div> <div class="form-group"> <button class="btn btn-primary" type="submit">Register</button> </div> <pre> {{theForm | json}} </pre> </form></div><script src="../node_modules/angular/angular.min.js"></script><script src="second.js"></script></body></html>
● 給form加上novalidate="novalidate"意味著表單將不再使用HTML5驗證特性
● 給form加上name="theForm"意味著表單的名稱是theForm。如何使用theForm,比如我們驗證表單是否被修改過theForm.$submitted
● 通過ng-submit提交表單
● formModel是$scope中的一個屬性
● 對錶單的Email進行了手動驗證,使用了AngularJS表單的眾多屬性,比如theForm.email.$valid,theForm.$pristine,theForm.$submitted, theForm.email.$error.required,theForm.email.$error.email
● 通過<pre>{{theForm | json}}</pre>把AngularJS表單的所有屬性都列印出來
{ "$error": { "required": [ { "$validators": {}, "$asyncValidators": {}, "$parsers": [], "$formatters": [ null ], "$viewChangeListeners": [], "$untouched": true, "$touched": false, "$pristine": true, "$dirty": false, "$valid": false, "$invalid": true, "$error": { "required": true }, "$name": "email", "$options": null } ] }, "$name": "theForm", "$dirty": false, "$pristine": true, "$valid": false, "$invalid": true, "$submitted": false, "email": { "$validators": {}, "$asyncValidators": {}, "$parsers": [], "$formatters": [ null ], "$viewChangeListeners": [], "$untouched": true, "$touched": false, "$pristine": true, "$dirty": false, "$valid": false, "$invalid": true, "$error": { "required": true }, "$name": "email", "$options": null }, "sex": { "$validators": {}, "$asyncValidators": {}, "$parsers": [], "$formatters": [], "$viewChangeListeners": [], "$untouched": true, "$touched": false, "$pristine": true, "$dirty": false, "$valid": true, "$invalid": false, "$error": {}, "$name": "sex", "$options": null }}
以上,凡是有name屬性的input都被顯示在上面。
在second.js檔案中定義了module,controller以及提交表單的方法。
var myApp1 = angular.module('myApp1',[]); myApp1.controller('myCtrl1', function($scope, $http){ $scope.formModel = {}; $scope.onSubmit = function(){ $http.post('someurl',$scope.formModel) .success(function(data){ console.log(':)'); }) .error(function(data){ console.log(':('); }); console.log($scope.formModel); };});
以上的表單驗證方式好處是可控性強,但相對繁瑣。
二、自動驗證
AngularJS的另外一種表單驗證方式是自動驗證,即通過directive來實現,除了AngularJS內建的directive,還需要用到angular-auto-validate這個第三方module。
有關angular-auto-validate:
● 安裝:npm i angular-auto-validate
● 引用:<script src="../node_modules/angular-auto-validate/dist/jcs-auto-validate.min.js"></script>
● module依賴:var myApp = angular.module("app", ["jcs-autoValidate"]);
為了實現錯誤資訊本地化,還需要angular-localize這個第三方module:
● 安裝:npm install angular-localize --save
● module依賴:var myApp = angular.module("app", ["localize"]);
● 引用:
<script src="../node_modules/angular-sanitize/angular-sanitize.min.js"></script><script src="../node_modules/angular-localize/angular-localize.min.js"></script>
此外,當點擊提交表單按鈕,需要禁用按鈕並顯示一種等待效果,需要用到angular-ladda這個第三方module:
● 安裝:bower install angular-ladda --save
● module依賴:var myApp = angular.module("app", ["angular-ladda"]);
● 引用:
<link rel="stylesheet" href="../bower_components/ladda/dist/ladda-themeless.min.css"/><script src="../bower_components/ladda/dist/spin.min.js"></script><script src="../bower_components/ladda/dist/ladda.min.js"></script><script src="../bower_components/angular-ladda/dist/angular-ladda.min.js"></script>
頁面如下:
<!DOCTYPE html><html lang="en" ng-app="myApp1"><head> <meta charset="gb2312"> <title></title> <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css"/> <link rel="stylesheet" href="../bower_components/ladda/dist/ladda-themeless.min.css"/> <link rel="stylesheet" href="../css/main.css"/></head><body><nav > <div class="container"> <div class="navbar-header"> <a href="/" class="navbar-brand">Form Validating Auto</a> </div> </div></nav> <div class="container main-content" ng-controller="myCtrl1"> <!--novalidate讓表單不要使用html驗證--> <!--theForm變成scope的一個欄位--> <form ng-submit="onSubmit()" novalidate="novalidate"> <div class="form-group"> <label for="name" class="control-label">Name</label> <input type="text" class="form-control" id="name" ng-model="formModel.name" required="required"/> </div> <div class="form-group"> <label for="email" class="control-label">Email</label> <input type="email" class="form-control" id="email" ng-model="formModel.email" required="required"/> </div> <div class="form-group"> <label for="username" class="control-label">Username</label> <input type="text" class="form-control" id="username" ng-model="formModel.username" required="required" ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" ng-pattern-err-type="badUsername" /> </div> <div class="form-group"> <label for="age" class="control-label">Age</label> <input type="number" class="form-control" id="age" ng-model="formModel.age" required="required" min="18" max="65" ng-min-err-type="tooYoung" ng-max-err-type="tooOld" /> </div> <div class="form-group"> <label for="sex" class="control-label">Sex</label> <select name="sex" id="sex" class="form-control" ng-model="formModel.sex" required="required"> <option value="">Please choose</option> <option value="male">Mail</option> <option value="femail">Femail</option> </select> </div> <div class="form-group"> <label for="password" class="control-label">Password</label> <input type="text" class="form-control" id="password" ng-model="formModel.password" required="required" ng-minlength="6"/> </div> <div class="form-group"> <!--<button class="btn btn-primary" ng-click="onSubmit()">Register</button>--> <button class="btn btn-primary" ladda = "submitting" data-style="expand-right" type="submit"> <span ng-show="submitting">正在註冊...</span> <span ng-show="!submitting">註冊</span> </button> </div> <pre> {{formModel | json}} </pre> </form></div><script src="../node_modules/angular/angular.min.js"></script> <script src="form_validation_auto.js"></script><script src="../node_modules/angular-auto-validate/dist/jcs-auto-validate.min.js"></script><script src="../node_modules/angular-sanitize/angular-sanitize.min.js"></script><script src="../node_modules/angular-localize/angular-localize.min.js"></script> <script src="../bower_components/ladda/dist/spin.min.js"></script><script src="../bower_components/ladda/dist/ladda.min.js"></script><script src="../bower_components/angular-ladda/dist/angular-ladda.min.js"></script> </body></html>
以上,先看提交按鈕:
<div > <!--<button class="btn btn-primary" ng-click="onSubmit()">Register</button>--> <button class="btn btn-primary" ladda = "submitting" data-style="expand-right" type="submit"> <span ng-show="submitting">正在註冊...</span> <span ng-show="!submitting">註冊</span> </button></div>
● ladda屬性值為bool值,true表示顯示動態等待效果,false不顯示動態等待效果,這裡的submitting是scope中的一個屬性
● data-style="expand-right"表示在按鈕的右側顯示動態等待效果
再拿表單中的Age欄位來說:
<div > <label for="age" class="control-label">Age</label> <input type="number" class="form-control" id="age" ng-model="formModel.age" required="required" min="18" max="65" ng-min-err-type="tooYoung" ng-max-err-type="tooOld" /></div>
其中,min, max為AgularJS的directive,而ng-min-err-type是angular-auto-validate的directive。這裡遵循的慣例是ng-AngularJS表單驗證的directive名稱-err-type,而tooYoung和tooOld的作用是什麼,又是在哪裡用上了呢?
是在module層面用上了,定義在了form_validation_auto.js檔案中。
var myApp1 = angular.module('myApp1',['jcs-autoValidate','localize','angular-ladda']); myApp1.run(function(defaultErrorMessageResolver){ defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages){ errorMessages['tooYoung'] = '年齡必須小於{0}'; errorMessages['tooOld'] = '年齡不能大於{0}'; errorMessages['badUsername'] = '使用者名稱只能包含數字、字母或底線'; });}); myApp1.controller('myCtrl1', function($scope, $http){ $scope.formModel = {}; $scope.submitting = false; $scope.onSubmit = function(){ $scope.submitting = true; console.log('已提交'); console.log($scope.formModel); $http.post('url',$scope.formModel) .success(function(data){ console.log(':)'); $scope.submitting = false; }) .error(function(data){ console.log(':('); $scope.submitting = false; }); };});
以上,在run方法中使用angular-auto-validate的defaultErrorMessageResolver服務,對錯誤資訊進行為了自訂。頁面上的tooYoung和tooOld和這裡的errorMessages['tooYoung']和errorMessages['badUsername']對應。
本文的全部內容就為大家介紹到這裡,希望對大家學習AngularJS實現表單驗證有所協助。