本文實例講述了Angular簡單驗證功能。分享給大家供大家參考,具體如下:
先來看看運行效果:
完整實例代碼如下:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>www.survivalescaperooms.com angular驗證功能</title> <script src="angular.min.js"></script> <style> input{ display: block; } ul li{ color: red; } </style> <script> angular.module("myapp",[]) .controller("demoC",function($scope){ $scope.datas = [{ id: 10011120, name: "iphoneX", num: 99 }, { id: 10011121, name: "華為mate10", num: 20 }, { id: 10011122, name: "vivoR12", num: 55 } ]; //定義一個數(shù)組 $scope.save=function(){ //創(chuàng)建一個存放錯誤信息數(shù)組 $scope.error_val=[]; var reg_id=/^/d{8,8}$/; //只能8位數(shù)字 if(!reg_id.test($scope.id)){ $scope.error_val.push("資產(chǎn)編號格式,必須為數(shù)字,且長度為8位"); } //資產(chǎn)名稱 if($scope.name==undefined||$scope.name==""){ $scope.error_val.push("資產(chǎn)名稱不能為空!"); }else{ for(var i in $scope.datas){ if($scope.name==$scope.datas[i].name){ $scope.error_val.push("資產(chǎn)名稱已經(jīng)存在"); break; //結(jié)束循環(huán),已經(jīng)查找到資產(chǎn)名稱不合法 } } } //資產(chǎn)數(shù)量 var reg_num=/^/d{1,}$/; //只能8位數(shù)字 if(!reg_num.test($scope.num)){ $scope.error_val.push("資產(chǎn)編號數(shù)量,必須為數(shù)字"); }else{ if($scope.num<=0){ $scope.error_val.push("資產(chǎn)編號數(shù)量必須大于0"); } } //何時添加進(jìn)行,何時不添加 if($scope.error_val.length==0){ $scope.datas.push({ id:$scope.id, name:$scope.name, num:$scope.num }); } } }) </script> </head> <body ng-app="myapp" ng-controller="demoC"> <table border="1px solid"> <tr> <td>資產(chǎn)編號</td> <td>資產(chǎn)名稱</td> <td>資產(chǎn)數(shù)量</td> </tr> <tr ng-repeat="d in datas"> <td>{{d.id}}</td> <td>{{d.name}}</td> <td>{{d.num}}</td> </tr> </table> <div> <form> 資產(chǎn)編號<input ng-model="id" /> 資產(chǎn)名稱<input ng-model="name" /> 資產(chǎn)數(shù)量<input ng-model="num" /> <div> <ul> <li ng-repeat="e in error_val"> {{e}} </li> </ul> </div> <button ng-click="save()"> 資產(chǎn)錄入 </button> </form> </div> </body></html>
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測試工具:
http://tools.VeVB.COm/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結(jié)》、《AngularJS入門與進(jìn)階教程》及《AngularJS MVC架構(gòu)總結(jié)》
希望本文所述對大家AngularJS程序設(shè)計有所幫助。
新聞熱點
疑難解答