首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:14:48
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选