AngularJS实现表单手动验证和表单自动验证
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实现表单验证有所帮助。
下一篇: 看完地铁看蓝翔!谁家的事件营销做得最好?