本文實例講述了AngularJS學習筆記之表單驗證功能。分享給大家供大家參考,具體如下:
一、執行基本的表單驗證
<!DOCTYPE html><html ng-app='exampleApp'> <head> <meta charset="UTF-8"> <title>表單</title> <script src="../../js/angular.min.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" type="text/css" href="../../css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" /> <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" /> <script type="text/javascript"> angular.module('exampleApp',[]) .controller('defaultCtrl',function($scope){ $scope.addUser=function(userDetails){ $scope.message=userDetails.name+"("+userDetails.email+")("+userDetails.agreed+")" } $scope.message='Ready'; }); </script> </head> <body> <div id="todoPanel" class="panel" ng-controller='defaultCtrl'> <form name='myForm' novalidate ng-submit='addUser(newUser)'> <div class="well"> <div class="form-group"> <label for="">Name:</label> <input type="text" name='userName' class="form-control" required ng-model='newUser.name'/> </div> <div class="form-group"> <label for="">Email:</label> <input type="email" name='userEmail' class="form-control" required ng-model='newUser.email'/> </div> <div class="checkbox"> <label for=""> <input type="checkbox" ng-model='newUser.agreed' required /> I agree to the terms and conditions </label> </div> <button type="submit" class="btn btn-primary btn-block" ng-disabled='myForm.$invalid'>OK</button> </div> <div class="well"> message:{{message}} <div> valid:{{myForm.$valid}} </div> </div> </form> </div> </body></html>在上述例子中,該HTML文檔被瀏覽器加載時的初始狀態是:有三個input元素以及一個被禁用且無法單擊的ok按鈕,當在文本框中輸入值并且勾選了復選框之后,按鈕將變為可用,從而允許用戶提交表單。
1、增加表單元素
(1)首先需要在form上設置一個name屬性
(2)需要給表單增添novalidate屬性,該屬性用于告訴瀏覽器不要自己校驗表單,從而允許AngularJS不受干擾的工作
(3)ng-submit指令為表單提交事件指定一個自定義的響應行為,將在用戶提交表單時觸發
2、使用校驗屬性
新聞熱點
疑難解答
圖片精選