当前位置:Gxlcms > JavaScript > AngularJS学习笔记之表单验证功能实例详解

AngularJS学习笔记之表单验证功能实例详解

时间:2021-07-01 10:21:17 帮助过:10人阅读

本文实例讲述了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、使用校验属性

(1)为各个想要验证的元素添加name属性,这样可以访问到Angularjs所提供的各种特殊的变量
(2)设置type属性,这个属性指定了input元素将要接收的数据类型,这些类型告诉angularjs需要什么样的校验
(3)指定required属性,这个属性指定用户必须为待校验的表单提供一个输入值
(4)在本例中input元素都使用ng-model指令来设置隐式定义的newUser对象的一个属性

3、监控表单的有效性

AngularJS中用来替换标准表单元素的指令定义了一些特殊的变量,可以用来检查表单中各个元素或整个表单的有效性状态。

$pristine:如果用户没有与元素/表单产生交互,则返回true
$dirty:如果用户与元素/表单产生过交互,则返回true
$valid:当元素/表单内容的校验结果为有效时则返回true
$invalid:当元素/表单内容的校验结果为无效时则返回true
$error:提供校验错误的详情信息

二、提供表单校验反馈信息

在上面的例子中展示的效果是比较简单的,ok按钮将一直被禁用,直到所有的input元素可用,以阻止用户输入错误格式的或未填完的数据。在接下来我们将演示AngularJS为报告实时的校验信息

1、使用css提供校验反馈信息

ng-pristine:用户未曾交互过的元素被添加到这个类
ng-dirty:用户曾经交互过的元素被添加到这个类
ng-valid:校验结果为有效的元素在这个类中
ng-invalid:校验结果为无效的元素在这个类中

下面我们来看具体用法:

<!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>

在上述例子中,我们定义了四个样式,头两个样式用于选择属于ng-dirty类成员的元素,仅在用户与之交互后应用到相应元素上。内容有效的元素是ng-valid类的成员,会被渲染为淡绿色背景,内容无效的元素是ng-invalid类的成员,会被渲染为淡粉色背景

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>

在本例中新增了一个新的div元素用于给用户显示校验提示信息,新的div元素的可见性是受ng-show指令控制的,将会在input元素被输入值,且输入值未通过校验时显示该元素。这里是联合使用form元素的name值和input的name值来访问input元素的。在这个例子中,我们使用特殊校验变量和其他指令联合使用以增强用户体验。但是这样可能会使页面增加大量的相同冗余信息的元素,接下来我们做简化

<!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>

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》

希望本文所述对大家AngularJS程序设计有所帮助。

人气教程排行