AngularJs的一個簡單的表單驗證

來源:互聯網
上載者:User

標籤:led   text   val   nbsp   har   min   沒有   logs   lang   

最近學習了AngularJs架構,覺得確實特別有用。之前學習了一點點的ASP.NET,它的控制項也是挺好的,不過還是沒有AngularJs輕巧。

定義一個應用程式myApp,一個控制器。接著是表單的驗證。

AngularJs中,表單控制項的HTML元素有:input select button textarea元素

其實還算是很簡單的例子。

不過我覺得對比起ASP那種龐大的控制項來說,它確實很輕巧。

 

AngularJS 輸入驗證
$dirty    表單有填寫記錄
$valid    欄位內容合法的
$invalid   欄位內容是非法的
$pristine   表單沒有填寫記錄

原來這四個值是不知道怎麼使用,後來發現,結合表單使用。

我覺得特別有意思的是最後那個提交按鈕的disabled的屬性,如果兩個輸入框中任何一個沒有填寫或者沒有填寫正確,都是不可用狀態。

 

 

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4     <meta charset="UTF-8"> 5     <title>表單驗證的例子</title> 6     <script src="js/angular.min.js"></script> 7     <script> 8         var app=angular.module(‘myApp‘,[]); 9         app.controller(‘validCtrl‘,function($scope){10             $scope.username="SliyCat";11             $scope.useremail="[email protected]"12         });13     </script>14 </head>15 <body>16     <form ng-app="myApp" ng-controller="validCtrl" name="login">17         <p>使用者註冊</p>18         <div>19             <label>UserName:</label>20             <input type="text" name="username" ng-model="username" required>21             <span ng-show="login.username.$dirty && login.username.$invalid">22                 <span ng-show="login.username.$error.required">使用者名稱不可為空</span>23             </span>24         </div>25         <div>26             <label>Email:</label>27             <input type="email" name="useremail" ng-model="useremail" required>28             <span ng-show="login.useremail.$dirty&&login.useremail.$invalid">29                 <span ng-show="login.useremail.$error.required">30                     郵箱不可為空31                 </span>32                 <span ng-show="login.useremail.$error.email">33                     非法格式34                 </span>35             </span>36         </div>37         <div>38             <input type="submit" name="okey" value="Next" ng-disabled="(login.username.$dirty && login.username.$invalid)||(login.useremail.$dirty&&login.useremail.$invalid)">39         </div>40     </form>41 </body>42 </html>

 

AngularJs的一個簡單的表單驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.