Angular簡單驗證功能示例
本文實例講述了Angular簡單驗證功能。分享給大家供大家參考,具體如下:
先來看看運行效果:

完整實例代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>www.fzitv.net 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");
}
}
//何時添加進行,何時不添加
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款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結(jié)》、《AngularJS入門與進階教程》及《AngularJS MVC架構(gòu)總結(jié)》
希望本文所述對大家AngularJS程序設(shè)計有所幫助。
相關(guān)文章
Angular2 Service實現(xiàn)簡單音樂播放器服務(wù)
本篇文章主要介紹了Angular2 Service實現(xiàn)簡單音樂播放器服務(wù) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
AngularJS基礎(chǔ) ng-model 指令詳解及示例代碼
本文主要介紹AngularJS ng-model 指令,這里幫大家整理了ng-model的基本資料,并附有示例代碼,有需要的小伙伴可以參考下2016-08-08
angular4自定義組件非input元素實現(xiàn)ngModel雙向數(shù)據(jù)綁定的方法
這篇文章主要介紹了angular4自定義組件非input元素實現(xiàn)ngModel雙向數(shù)據(jù)綁定的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
Angularjs實現(xiàn)下拉框聯(lián)動的示例代碼
Angular實現(xiàn)的簡單查詢天氣預(yù)報功能示例

