溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

AngularJS學(xué)習(xí)筆記之表單驗(yàn)證功能實(shí)例詳解

發(fā)布時(shí)間:2020-09-27 12:41:49 來源:腳本之家 閱讀:159 作者:Annexu1991 欄目:web開發(fā)

本文實(shí)例講述了AngularJS學(xué)習(xí)筆記之表單驗(yàn)證功能。分享給大家供大家參考,具體如下:

一、執(zhí)行基本的表單驗(yàn)證

<!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文檔被瀏覽器加載時(shí)的初始狀態(tài)是:有三個(gè)input元素以及一個(gè)被禁用且無法單擊的ok按鈕,當(dāng)在文本框中輸入值并且勾選了復(fù)選框之后,按鈕將變?yōu)榭捎?,從而允許用戶提交表單。

1、增加表單元素

(1)首先需要在form上設(shè)置一個(gè)name屬性
(2)需要給表單增添novalidate屬性,該屬性用于告訴瀏覽器不要自己校驗(yàn)表單,從而允許AngularJS不受干擾的工作
(3)ng-submit指令為表單提交事件指定一個(gè)自定義的響應(yīng)行為,將在用戶提交表單時(shí)觸發(fā)

2、使用校驗(yàn)屬性

(1)為各個(gè)想要驗(yàn)證的元素添加name屬性,這樣可以訪問到Angularjs所提供的各種特殊的變量
(2)設(shè)置type屬性,這個(gè)屬性指定了input元素將要接收的數(shù)據(jù)類型,這些類型告訴angularjs需要什么樣的校驗(yàn)
(3)指定required屬性,這個(gè)屬性指定用戶必須為待校驗(yàn)的表單提供一個(gè)輸入值
(4)在本例中input元素都使用ng-model指令來設(shè)置隱式定義的newUser對(duì)象的一個(gè)屬性

3、監(jiān)控表單的有效性

AngularJS中用來替換標(biāo)準(zhǔn)表單元素的指令定義了一些特殊的變量,可以用來檢查表單中各個(gè)元素或整個(gè)表單的有效性狀態(tài)。

$pristine:如果用戶沒有與元素/表單產(chǎn)生交互,則返回true
$dirty:如果用戶與元素/表單產(chǎn)生過交互,則返回true
$valid:當(dāng)元素/表單內(nèi)容的校驗(yàn)結(jié)果為有效時(shí)則返回true
$invalid:當(dāng)元素/表單內(nèi)容的校驗(yàn)結(jié)果為無效時(shí)則返回true
$error:提供校驗(yàn)錯(cuò)誤的詳情信息

二、提供表單校驗(yàn)反饋信息

在上面的例子中展示的效果是比較簡單的,ok按鈕將一直被禁用,直到所有的input元素可用,以阻止用戶輸入錯(cuò)誤格式的或未填完的數(shù)據(jù)。在接下來我們將演示AngularJS為報(bào)告實(shí)時(shí)的校驗(yàn)信息

1、使用css提供校驗(yàn)反饋信息

ng-pristine:用戶未曾交互過的元素被添加到這個(gè)類
ng-dirty:用戶曾經(jīng)交互過的元素被添加到這個(gè)類
ng-valid:校驗(yàn)結(jié)果為有效的元素在這個(gè)類中
ng-invalid:校驗(yàn)結(jié)果為無效的元素在這個(gè)類中

下面我們來看具體用法:

<!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>
    <style type="text/css">
      form .ng-invalid.ng-dirty{background-color: lightpink;}
      form .ng-valid.ng-dirty{background-color: lightgreen;}
      span.summary.ng-invalid{color: red;font-weight: bold;}
      span.summary.ng-valid{color: green;}
    </style>
  </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:
            <span class="summary" ng-class="myForm.$valid?'ng-valid':'ng-invalid'">
              {{myForm.$valid}}
            </span>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

在上述例子中,我們定義了四個(gè)樣式,頭兩個(gè)樣式用于選擇屬于ng-dirty類成員的元素,僅在用戶與之交互后應(yīng)用到相應(yīng)元素上。內(nèi)容有效的元素是ng-valid類的成員,會(huì)被渲染為淡綠色背景,內(nèi)容無效的元素是ng-invalid類的成員,會(huì)被渲染為淡粉色背景

2、使用特殊變量來提供反饋信息

<!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>
    <style type="text/css">
      form .ng-invalid-required.ng-dirty{background-color: lightpink;}
      form .ng-invalid-email.ng-dirty{background-color: lightgoldenrodyellow;}
      form .ng-valid.ng-dirty{background-color: lightgreen;}
      span.summary.ng-invalid{color: red;font-weight: bold;}
      span.summary.ng-valid{color: green;}
      div.error{color:red;font-weight: bold;}
    </style>
  </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="">Email:</label>
            <input type="email" name='userEmail' class="form-control" required ng-model='newUser.email'/>
            <div class="error" ng-show="myForm.userEmail.$invalid&&myForm.userEmail.$dirty">
              <span ng-show="myForm.userEmail.$error.email">
                please enter a valid email address
              </span>
              <span ng-show="myForm.userEmail.$error.required">
                please enter a value
              </span>
            </div>
          </div>
          <button type="submit" class="btn btn-primary btn-block" ng-disabled='myForm.$invalid'>OK</button>
        </div>
      </form>
    </div>
  </body>
</html>

在本例中新增了一個(gè)新的div元素用于給用戶顯示校驗(yàn)提示信息,新的div元素的可見性是受ng-show指令控制的,將會(huì)在input元素被輸入值,且輸入值未通過校驗(yàn)時(shí)顯示該元素。這里是聯(lián)合使用form元素的name值和input的name值來訪問input元素的。在這個(gè)例子中,我們使用特殊校驗(yàn)變量和其他指令聯(lián)合使用以增強(qiáng)用戶體驗(yàn)。但是這樣可能會(huì)使頁面增加大量的相同冗余信息的元素,接下來我們做簡化

<!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';
        $scope.getError=function(error){
          if(angular.isDefined(error)){
            if(error.required){
              return 'please enter a value';
            }else if(error.email){
              return 'please enter a valid email address';
            }
          }
        }
      });
    </script>
    <style type="text/css">
      form .ng-invalid-required.ng-dirty{background-color: lightpink;}
      form .ng-invalid-email.ng-dirty{background-color: lightgoldenrodyellow;}
      form .ng-valid.ng-dirty{background-color: lightgreen;}
      span.summary.ng-invalid{color: red;font-weight: bold;}
      span.summary.ng-valid{color: green;}
      div.error{color:red;font-weight: bold;}
    </style>
  </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="">Email:</label>
            <input type="email" name='userEmail' class="form-control" required ng-model='newUser.email'/>
            <div class="error" ng-show="myForm.userEmail.$invalid&&myForm.userEmail.$dirty">
              {{getError(myForm.userEmail.$error)}}
            </div>
          </div>
          <button type="submit" class="btn btn-primary btn-block" ng-disabled='myForm.$invalid'>OK</button>
        </div>
      </form>
    </div>
  </body>
</html>

更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結(jié)》、《AngularJS入門與進(jìn)階教程》及《AngularJS MVC架構(gòu)總結(jié)》

希望本文所述對(duì)大家AngularJS程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI