AngularJS系列(十)——表单的重置和验证

  • 2019 年 10 月 30 日
  • 筆記

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/77897260

表单重置

表单重置实例

<div ng-app="myApp"ng-controller="formCtrl">   <form novalidate>     First Name:<br>     <input ng-model="user.firstName" /><br>     Last Name:<br>     <input ng-model="user.lastName" />     <br><br>             <button ng-click="rest()">重置</button>   </form>   <p>form = {{user }}</p>   <p>master = {{master}}</p>  </div>
<script>  var app = angular.module('myApp', []);  app.controller('formCtrl', function($scope){     $scope.master = {firstName:"John", lastName:"Doe"};     $scope.rest = function (){                     $scope.user= angular.copy($scope.master);           }           $scope.rest();  });  </script>

表单验证

AngularJS表单的内置验证

表单的状态有

下面是表单验证提示和是否能提交的例子

<form ng-app="myApp"ng-controller="validateCtrl"  name="myForm" novalidate>  <p>用户名:<br>  <input type="text"name="user" ng-model="user" requiredng-minlength="3" ng-maxlength="8">  <spanng-hide="myForm.user.$valid" style="color:red">           <spanng-show="myForm.user.$error.required">用户名是必须的。</span>           <spanng-show="myForm.user.$error.minlength">合法输入必须不小于3字符</span>           <spanng-show="myForm.user.$error.maxlength">合法输入必须不大于8字符</span>  </span>  </p>  <p>邮箱:<br>  <input type="email"name="email" ng-model="email" required>  <span ng-hide="myForm.email.$valid"style="color:red">           <spanng-show="myForm.email.$error.repuired">邮箱地址是必须的</span>           <spanng-show="myForm.email.$error.email">非法的邮箱地址。</span>  </span>  </p>  <p>  <input type="submit"ng-disabled="myForm.$invalid" />  </p>  </form>
<script>  var app = angular.module('myApp', []);  app.controller('validateCtrl',function($scope) {     $scope.user = 'John Doe';     $scope.email = '[email protected]';  });  </script>

实例解析

1. 表单验证表达式必须从表单开始,即myForm.user.$valid而不能是user.$valid。

2. 表单验证不通过可以通过myForm.email.$error.xxx得到是什么原因不通过

3. ng-disabled="myForm.$invalid"作用是表单验证不通过时,提交按钮不可用