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>
原文地址:https://www.cnblogs.com/luckyflower/p/4172957.html