Home >Web Front-end >JS Tutorial >Detailed interpretation of form validation programming in AngularJS_AngularJS
Demand
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
Angular also provides classes for forms and their input boxes so that you can set their styles according to each state.
Access form properties
Set up our form
We will use a simple form to demonstrate.
We will need two files:
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:
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.
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属性从而决定是否显示错误信息.
格局类
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错误类.
只在提交表单后显示错误信息
有时候不想在用户正在输入的时候显示错误信息. 当前错误信息会在用户输入表单时立即显示. 由于Angular很棒的数据绑定特性,这是可以发生的. 因为所有的事务都可以在一瞬间发生改变,这在表单验证时会有副作用.
对于你想要只在表单正要提交之后才显示错误消息的场景, 你就需要对上面的代码做一些小调整.
现在,只有在submitted变量被设置为true时才会显示错误信息.
只有在输入框之外点击时才显示错误消息
只有在输入框之外点击时才显示错误消息(也被叫做失去焦点 blur) 这一需求比在提交时验证要复杂一点. 在失去焦点时验证表单需要一个custom指令. 这是一个可以让你操作DOM的指令.
我们正在写一篇文章专门讨论此话题。同时,还有其他的一些资源讨论了创建custom指令来处理失去焦点的情况:
全部完成
现在一旦我们正确填写了所有的信息,我们的表单提交按钮就能使用了. 一旦我们提交了表单,我们将会见到我们设置的弹出消息.
用了几行我们就可以:
如你所见,我们使用了Angular内置的表单验证技术来创建一个客户端验证表单.