標籤:
常用的表單驗證指令 (基本概念)1. 必填項驗證
某個表單輸入是否已填寫,只要在輸入欄位元素上添加HTML5標記required即可:
<input type="text" required />
2. 最小長度
驗證表單輸入的文本長度是否大於某個最小值,在輸入欄位上使用指令ng-minleng= "{number}":
<input type="text" ng-minlength="5" />
3. 最大長度
驗證表單輸入的文本長度是否小於或等於某個最大值,在輸入欄位上使用指令ng-maxlength="{number}":
<input type="text" ng-maxlength="20" />
4. 模式比對
使用ng-pattern="/PATTERN/"來確保輸入能夠匹配指定的Regex:
<input type="text" ng-pattern="/[a-zA-Z]/" />
5. 電子郵件
驗證輸入內容是否是電子郵件,只要像下面這樣將input的類型設定為email即可:
<input type="email" name="email" ng-model="user.email" />
6. 數字
驗證輸入內容是否是數字,將input的類型設定為number:
<input type="number" name="age" ng-model="user.age" />
7. URL
驗證輸入內容是否是URL,將input的類型設定為 url:
<input type="url" name="homepage" ng-model="user.facebook_url" />
我們使用了 ng-show指令, color:red 在郵件是 $dirty 或 $invalid 才顯示:
| 屬性 |
描述 |
| $dirty |
表單有填寫記錄 |
| $valid |
欄位內容合法的 |
| $invalid |
欄位內容是非法的 |
| $pristine |
表單沒有填寫記錄 |
樣本(以郵箱為例+Regex 引入angular+bootstrap)
ngRegex寫法:
ng-pattern=" /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/" //郵箱驗證
<body ng-Controller="MyController"> //ng-app標在html標籤上<div class="col-md-6"> <form role="form" name="myForm" ng-submit="submitForm(myForm.$valid)" class="form-horizontal" novalidate> <div class="form-group has-feedback"> <div class="col-md-4"> <label for="email"> 電子郵件</label> </div> <div class="col-md-6"> <input type="email" id="email" name="email" ng-minlength="5" ng-maxlength="30" ng-pattern=" /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/" ng-model="user.email" required class="form-control" /> <span class="glyphicon glyphicon-ok form-control-feedback" ng-show="myForm.email.$dirty && myForm.email.$valid"></span> </div> <div class="col-md-2"> <span style="color:red" class="" ng-show="myForm.email.$dirty && myForm.email.$invalid">郵箱格式錯誤!</span> </div> </div> <div class="form-group text-center"> <input class="btn btn-primary btn-lg" ng-disabled="myForm.$invalid" type="submit" value="提交" /> </div> </form></div><script> angular.module(‘myTest‘, []) .controller(‘MyController‘, function($scope) { $scope.submitForm = function(isValid) { if (!isValid) { alert(‘驗證失敗‘); } }; } );</script></body>
也可以更詳盡的支出單個錯誤:
<div ng-show="myForm.email.$dirty && myForm.email.$error.maxlength" class="alert alert-danger help-block"> 郵箱長度不能超過30位</div><div ng-show="myForm.email.$dirty && myForm.email.$error.minlength" class="alert alert-danger help-block"> 郵箱長度不能小於5位</div><div ng-show="myForm.email.$dirty && myForm.email.$error.email" class="alert alert-danger help-block"> 郵箱格式不正確</div>
徹底弄懂angularJS表單驗證