angularJS添加form驗證:自定義驗證


剛學習form驗證。不得不說form驗證是比較豐富的。下面來個小例子。
1、情景:看電影選座位!
2、具體要求:當輸入座位號時,進行校驗。其中1已經被選。如果輸入為1,則提交按鈕置為無效,並且給出提示,如果輸入為2,則不給出提示,允許提交
3、實際效果:


4、代碼示例:

 1 <!DOCTYPE HTML>
 2 <html ng-app="app">
 3 <head>
 4 <meta charset="utf-8"/>
 5 <script src="jquery-1.10.2.min.js"></script>
 6 <script src="angular.js"></script>
 7 <style type="text/css">
 8   input.ng-invalid.ng-dirty {
 9     background-color: yellow;
10   }
11 </style>
12 </head>
13 <body ng-controller="controller">
14 <h1>正確性校驗</h1>
15 <form name="myform" novalidate>
16     請輸入你選的電影座位順序
17     <input type="text"  ng-model="seq"  name="seq" ng-keyup="isDup(seq);"/>
18     <span ng-show="myform.seq.$error.seq">座位已經有人坐了!</span>
19     <button ng-disabled="myform.$invalid" id="btn">提交</button>
20 </form>
21 
22 <script>
23 angular.module('app',[]).controller("controller",function($scope){
24     $scope.flag = false;
25     $scope.seq=1;//初始值為1,並且1已經被選了
26     $scope.isDup=function(seq){
27         if(seq == 1)
28         {
29             //var btn=document.getElementById('btn');
30             //btn.setAttribute('disabled','disabled');
31             $scope.myform.seq.$setValidity("seq", false)
32             //$scope.seq=2;
33         }
34         else{
35             //var btn=document.getElementById('btn');
36             //btn.removeAttribute('disabled','disabled');
37             $scope.myform.seq.$setValidity("seq", true);
38             //$scope.seq=1;
39         }
40     }
41 });
42 
43 </script>
44 </body>
45 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM