Home >Web Front-end >JS Tutorial >Detailed interpretation of form validation programming in AngularJS_AngularJS

Detailed interpretation of form validation programming in AngularJS_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:53:591235browse

Demand

  • Name required
  • Username is optional, minimum length is 3, maximum length is 8
  • Email is not required, but must be a legal email
  • Forms that fail verification cannot be submitted
  • Display a required or illegal email format error message
  • If submitted correctly, a congratulatory message will pop up

Now that we know our goal, let’s build this thing together.

Angular form properties $valid, $invalid, $pristine, $dirty

Angular provides properties about forms to help us validate forms. They provide us with various information about a form and its inputs, and apply to the form and inputs.
Attribute class
Description

  • $valid ng-valid Boolean tells us whether this item is currently verified based on the rules you set
  • $invalid ng-invalid Boolean tells us whether this item currently fails verification based on the rules you set
  • $pristine ng-pristine Boolean True if the form or input box is not used
  • $dirty ng-dirty Boolean True if the form or input box is used

Angular also provides classes for forms and their input boxes so that you can set their styles according to each state.
Access form properties

  • Orientation form: 2e6b4a1960377ae11eb6a93718d8c453.06aa1095e228e0c68f44aa16caf48a1d
  • Access an input box: 2e6b4a1960377ae11eb6a93718d8c453.eddb2c4e7966b7dc34dd125cd9f6b1ef.06aa1095e228e0c68f44aa16caf48a1d

Set up our form

We will use a simple form to demonstrate.

201561995404669.png (765×364)

We will need two files:

  1. index.html The code we use to display the form
  2. app.js Our Angular application and controller (barely any code)

Our Form Code index.html

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <!-- CSS ===================== -->
  <!-- load bootstrap -->
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> 
  <style>
    body   { padding-top:30px; }
  </style>
   
  <!-- JS ===================== -->
  <!-- load angular -->
  <script src="http://code.angularjs.org/1.2.6/angular.js"></script> 
  <script src="app.js"></script>
</head>
 
<!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
   
  <!-- PAGE HEADER -->
  <div class="page-header"><h1>AngularJS Form Validation</h1></div>
  
  <!-- FORM -->
  <!-- pass in the variable if our form is valid or invalid -->
  <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
 
    <!-- NAME -->
    <div class="form-group">
      <label>Name</label>
      <input type="text" name="name" class="form-control" ng-model="name" required>
    </div>
 
    <!-- USERNAME -->
    <div class="form-group">
      <label>Username</label>
      <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
    </div>
     
    <!-- EMAIL -->
    <div class="form-group">
      <label>Email</label>
      <input type="email" name="email" class="form-control" ng-model="email">
    </div>
     
    <!-- SUBMIT BUTTON -->
    <button type="submit" class="btn btn-primary">Submit</button>
     
  </form>
 
</div><!-- col-sm-8 -->
</div><!-- /container -->
</body>
</html>

Here are some key points:

  • novalidate: It will prevent the default HTML5 validation, because we will do it ourselves (our own will be better)
  • We applied ng-model on the input box to bind data from the form to angular variables
  • The ng-minlength and ng-maxlength on username will create its own rules
  • The name input box is required
  • The email input box has the attribute type="email"


Validation Rules

Angular has many validation rules, such as tong-min leng than dng-max length.

Angular can also configure its own rules. There are instructions in the Angular input guide.

<input
  ng-model="{ string }"
  name="{ string }"
  required
  ng-required="{ boolean }"
  ng-minlength="{ number }"
  ng-maxlength="{ number }"
  ng-pattern="{ string }"
  ng-change="{ string }">
</input>

Now that the form is created, create the Angular application and controller, ng-app ng-controller.
Applied Codeapp.js

// app.js
// create angular app
var validationApp = angular.module('validationApp', []);
 
// create angular controller
validationApp.controller('mainController', function($scope) {
 
  // function to submit the form after all validation has occurred      
  $scope.submitForm = function(isValid) {
 
    // check to make sure the form is completely valid
    if (isValid) {
      alert('our form is amazing');
    }
 
  };
 
});


Enable HTML5 validator's novalidate

We will use novalidate in our form. This is a good practice since we will be handling the validation ourselves. If we let our form do this, it would look ugly.

201561995443961.png (641×170)

Disable submit button ng-disabled

Now the real show begins. We start using Angular properties. First let's disable our submit button. If our form is $invalid, we just want to disable it.

<!-- index.html -->
...
 
  <!-- SUBMIT BUTTON -->
  <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>
 
...

With just a little code (ng-disabled), if our form is $invalid, the form buttons will be disabled.
This means that our name input field is required, and our email input field requires a valid email.

Use eng-show to display error messages

ng-valid and ng-invalid will automatically validate the input based on the provided form rules.

We add some error information in the input part, as long as it is not equal to $valid or has been used (it cannot be displayed as unused).

<!-- index.html -->
...
 
  <!-- NAME -->
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" ng-model="name" required>
    <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
  </div>
 
  <!-- USERNAME -->
  <div class="form-group">
    <label>Username</label>
    <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
    <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
    <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
  </div>
   
  <!-- EMAIL -->
  <div class="form-group">
    <label>Email</label>
    <input type="email" name="email" class="form-control" ng-model="email">
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
  </div>
 
...

就像这样 Angular 会根据规则来验证输入部分的$invalid 和 $pristine properties属性从而决定是否显示错误信息.

201561995503615.png (799×437)

格局类

Angular在验证输入或表单时的有效有否是已经提供了一些类,像是 (ng-valid,ng-invalid,ng-pristineandng-dirty).

你可以编辑自己喜欢的CSS . 你可以私有定制化这些类来实现特定的场景应用.
 

.ng-valid     { }
.ng-invalid   { }
.ng-pristine   { }
.ng-dirty     { }
 
/* really specific css rules applied by angular */
.ng-invalid-required     { }
.ng-invalid-minlength     { }
.ng-valid-max-length     { }

使用 ng-class 根据条件添加类

因为我们使用了 Bootstrap, 我们将就使用它们提供的类(has-error). 这样就能围绕我们的form-group获得漂亮的错误信息和颜色.

ng-class 允许我们基于一个表达式添加类. 在这种情况下,我们想要想我们的form-group添加一个 has-error 类,如果输入框的状态是$invalid或者不是pristine的话.

其工作的方式是 ng-class="{ 64e942f46d2e9af455b3f1c4acffb72e : 18f3084cc35bfabb3ad3e5c76b34d42c }". 更多的信息,请读一读 Angular ngClass 文档吧.

 

<!-- index.html -->
...
 
  <!-- NAME -->
  <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
    <label>Name</label>
    <input type="text" name="name" class="form-control" ng-model="user.name" required>
    <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
  </div>
   
  <!-- USERNAME -->
  <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
    <label>Username</label>
    <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
    <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
    <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
  </div>
     
  <!-- EMAIL -->
  <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }">
    <label>Email</label>
    <input type="email" name="email" class="form-control" ng-model="user.email">
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
  </div>
 
...

现在我们的表单就有了恰当的Bootstrap错误类.

201561995526100.png (770×449)

只在提交表单后显示错误信息

有时候不想在用户正在输入的时候显示错误信息. 当前错误信息会在用户输入表单时立即显示. 由于Angular很棒的数据绑定特性,这是可以发生的. 因为所有的事务都可以在一瞬间发生改变,这在表单验证时会有副作用.

对于你想要只在表单正要提交之后才显示错误消息的场景, 你就需要对上面的代码做一些小调整.

  •     你要去掉提交按钮上的ng-disabled,因为我们想要用户即使是在表单没有全部验证完的情况下也能点击提交.
  •     你要在表单已经被提交之后添加一个变量. 在你的 submitForm() 函数中, 只要加入 $scope.submitted = true 就行了;. 一旦表单被提交,它就会保存提交值为true的submitted变量.
  •     将错误规则从ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }" 调整为 ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine && submitted }". 这就确保了错误消息只会在表单被提交时被显示出来. 你也许会需要为这个变量调整所有其它的 ng-class 和 ng-show.

现在,只有在submitted变量被设置为true时才会显示错误信息.
 
只有在输入框之外点击时才显示错误消息

只有在输入框之外点击时才显示错误消息(也被叫做失去焦点 blur) 这一需求比在提交时验证要复杂一点. 在失去焦点时验证表单需要一个custom指令. 这是一个可以让你操作DOM的指令.

我们正在写一篇文章专门讨论此话题。同时,还有其他的一些资源讨论了创建custom指令来处理失去焦点的情况:

  •     http://coding-issues.blogspot.in/2013/10/angularjs-blur-directive.html
  •     http://blog.ejci.net/2013/08/06/dealing-with-focus-and-blur-in-angularjs-directives/
  •     http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview

全部完成

现在一旦我们正确填写了所有的信息,我们的表单提交按钮就能使用了. 一旦我们提交了表单,我们将会见到我们设置的弹出消息.

201561995546318.png (376×169)

用了几行我们就可以:

  •     进行输入框验证
  •     显示表单错误消息
  •     定制样式类
  •     自动禁止和启用表单
  •     定制规则

如你所见,我们使用了Angular内置的表单验证技术来创建一个客户端验证表单.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn