Detailed explanation of Form Verification programming in AngularJS, and angularjs forms
Requirement
- Name required
- Username is optional; minimum length: 3; maximum length: 8
- Email is not required, but must be a valid email
- Forms that fail verification cannot be submitted
- Displays a required or invalid email format error message.
- If the information is submitted correctly, a congratulation message is displayed.
Now we know our goal. Let's build this together.
Angular form attributes $ valid, $ invalid, $ pristine, $ dirty
Angular provides form attributes to help us verify the form. They provide us with a variety of information about a form and its input, and apply the form and input.
Attribute Class
Description
- $ Valid ng-valid Boolean tells us whether the current rule is verified based on your settings
- $ Invalid ng-invalid Boolean tells us whether the current verification based on your set rule has not passed
- $ Pristine ng-pristine Boolean True if the form or input box is not used
- $ Dirty ng-dirty Boolean True if a form or input box is used
Angular also provides a class for the form and its input box, so that you can set its style based on each status.
Access Form attributes
- Azimuth form: <form name>. <angular property>
- Access an input box: <form name>. <input name>. <angular property>
Set our form
We will use a simple form for demonstration.
We will need two files:
- Index.html: code used to display the form
- App. js our Angular application and controller (almost no code)
Our Form Code index.html
<!-- index.html --><!DOCTYPE html>
Some key points are listed here:
- Novalidate: it will organize the default HTML5 verification, because it will be done by ourselves (our own will be better)
- We applied ng-model in the input box to bind data from the form to the angular variable.
- Ng-minlength and ng-maxlength on username will create their own rules
- The name field is required.
- The email input box has the attribute type = "email"
Verification rules
Angular has many verification rules, such as tong-min leng than dng-max length.
Angular can also configure its own rules. Angular input instructions are provided.
<input ng-model="{ string }" name="{ string }" required ng-required="{ boolean }" ng-minlength="{ number }" ng-maxlength="{ number }" ng-pattern="{ string }" ng-change="{ string }"></input>
Now the form is created, and Angular application and controller are created, ng-app ng-controller.
Codeapp. js of the application
// app.js// create angular appvar validationApp = angular.module('validationApp', []); // create angular controllervalidationApp.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'); } }; });
Make the HTML5 validator's novalidate
We will use novalidate in our form. This is a good practice because we will handle the verification on our own. If we let our form do this, it looks ugly.
Disable the submit button ng-disabled
Now we have a really good show. We started to use Angular attributes. First, disable the submit button. If our form is $ invalid, we only want to disable it.
<!-- index.html -->... <!-- SUBMIT BUTTON --> <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button> ...
Use only a little code (ng-disabled). If our form is $ invalid, the form button will be disabled.
This means that our name input field is required, and the email input field requires a valid email.
Use eng-show to Display error messages
Ng-valid and ng-invalid will automatically verify the input validity Based on the provided form rules.
Add some error information in the input part as long as it is not equal to $ valid or it has been used (it cannot be displayed yet ).
<!-- 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> ...
In this way, Angular verifies the $ invalid and $ pristine properties attributes of the input part based on the rules to determine whether to display the error message.
Pattern
Angular has provided some classes for verifying whether the input or form is valid, such as (ng-valid, ng-invalid, ng-pristineandng-dirty ).
You can edit your favorite CSS. You can customize these classes to implement specific scenario applications.
.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 { }
Use ng-class to add classes based on conditions
Because Bootstrap is used, we will use the classes provided by them (has-error), so that we can get beautiful error messages and colors around our form-group.
Ng-class allows us to add classes based on an expression. in this case, we want to add an has-error class to our form-group, if the input box is in the status of $ invalid or not pristine.
The working method is ng-class = "{<class-you-want >:< expression to be evaluated> }". for more information, read the Angular ngClass document.
<!-- 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> ...
Now our form has the appropriate Bootstrap error class.
The error message is displayed only after the form is submitted.
Sometimes you do not want to display an error message when the user is entering it. the current error message is displayed immediately when the user enters the form. this can happen because Angular has a great data binding feature. because all transactions can be changed in an instant, this will have side effects in form verification.
For scenarios where you want to display error messages only after the form is submitted, you need to make some minor adjustments to the above Code.
- Remove ng-disabled from the submit button, because we want users to click submit even if the form is not fully verified.
- You need to add a variable after the form has been submitted. in your submitForm () function, you only need to add $ scope. submitted = true ;. once the form is submitted, it will save the submitted variable whose submission value is true.
- Set the error rule from ng-class = "{'has-error': userForm. name. $ invalid &&! UserForm. name. $ pristine} "adjusted to ng-class =" {'has-error': userForm. name. $ invalid &&! UserForm. name. $ pristine & submitted }". this ensures that the error message is only displayed when the form is submitted. you may need to adjust all other ng-class and ng-show for this variable.
The error message is displayed only when the submitted variable is set to true.
The error message is displayed only when you click outside the input box.
The error message (also called lost focus blur) is displayed only when you click outside the input box. This requirement is more complex than verification during submission. when the focus is lost, a custom command is required to verify the form. this is an instruction that allows you to operate the DOM.
We are writing an article dedicated to this topic. At the same time, there are other resources to discuss the situation of creating a m command to deal with the loss of focus:
- 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
Complete
Now, once we have entered all the information correctly, our form submission button can be used. Once we have submitted the form, we will see the pop-up message we set.
With a few lines, we can:
- Input box Verification
- Display form error messages
- Custom Style
- Automatic Form disabling and enabling
- Custom Rules
As you can see, we use Angular's built-in form verification technology to create a client verification form.