Detailed interpretation of form validation programming in ANGULARJS

Source: Internet
Author: User
Tags button type commit min requires valid


This article mainly introduces the detailed interpretation of angularjs in the form of validation programming, Angularjs is a very popular JavaScript library, need friends can refer to the



Demand



Name must be filled in



Username not required, minimum length 3, Maximum length 8



Email is not required, but must be legal email



Verify that an failed form cannot be submitted



Display an error message in a required or illegal email format



If submitted correctly, a congratulatory message pops up.



Now that you know what we're aiming for, let's build this thing together.



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



Angular provides properties for the form to help us validate the form. They provide us with a variety of information about a form and its input, and they apply to forms and inputs.



Attribute Class



Describe



$valid Ng-valid Boolean tells us that this is currently based on the rules you set to verify through



$invalid Ng-invalid Boolean tells us whether this is currently based on the rules you have set to verify that it failed



$pristine Ng-pristine Boolean True if the form or input box is not used



$dirty Ng-dirty Boolean If the form or input box is used to true



Angular also provides classes about the form and its input boxes so that you can set its style according to each state.



Accessing form Properties



Azimuth form:



.



Access an input box:..



To set up our form



We'll use a simple form to do the demo.



We will need two files:



Index.html the code we use to display the form



App.js our angular applications and controllers (almost no 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>

Some key points are listed here:



Novalidate: It will organize the default HTML5 validation, because it will be done by ourselves (our own will be better)



We applied Ng-model on the input box to bind the data from the form to the angular variable



Ng-minlength and Ng-maxlength on username will create their own rules.



The name input box is required



Email input box has attributes type= "email"



Validation rules



Angular has many validation rules, such as Tong-min Leng than Dng-max length.



Angular can also configure the rules yourself. Angular the instructions on the input guidelines.




<input ng-model= "{string}" Name= "{string}" required Ng-required= "{Boolean}" Ng-minlength= "{number}" Ng-maxlengt H= ' {number} ' ng-pattern= ' {string} ' ng-change= ' {string} ' > </input>


Now the form is built, then the angular application and the controller are created, Ng-app the ng-controller.



Application of Codeapp.js




App.js//Create angular app var Validationapp = angular.module (' Validationapp ', []); Create angular controller validationapp.controller (' Maincontroller ', function ($scope) {//function to submit the for M 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 Novalidate



We will use novalidate in our form. This is a good practice because we will handle the validation ourselves. If we make our form do this, it looks ugly.



Disable Submit button ng-disabled



Now the real drama is on. We started using the 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 bit of code (ng-disabled), if our form is $invalid, the form buttons will be disabled.



This means that our name input field is required, and the email input field requires a valid email.



displaying error messages with Eng-show



Ng-valid and Ng-invalid automatically verify the validity of the input based on the form rules provided.



Let's add some error information in the input section, as long as it does not equal $valid or has been used on the line (not shown yet to be used).




<!--index.html-->   <!--NAME--> <div class= "Form-group" > <label>Name</label> & Lt;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" 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>   ...


It's like this. Angular verifies the $invalid and $pristine properties Properties of the input section according to the rules to determine whether an error message is displayed.



Pattern class



Angular whether the validation of input or form is valid has been provided by some classes, such as (Ng-valid,ng-invalid,ng-pristineandng-dirty).



You can edit your favorite CSS. You can customize these classes privately to implement specific scenario applications.




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


Use Ng-class to add a class to a condition



Because we use Bootstrap, we will use the classes they provide (has-error). This will enable us to 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 a Has-error class to our form-group, if the status of the input box is $invalid or not pristine.



The way it works is ng-class= "{:}". For more information, please read the angular ngclass document.




<!--index.html-->   <!--NAME--> <div class= "Form-group" ng-class= "{' Has-error ': userform.na Me. $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--& Gt <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" 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 proper Bootstrap error class.



Display error messages only after submitting a form



Sometimes you don't want to display an error message when the user is typing. The current error message is displayed as soon as the user enters the form. This can happen because angular is a great data-binding feature. Because all transactions can change in a single moment, this can have side effects in form validation.



For scenarios where you want to display an error message only after the form is submitted, you need to make some minor adjustments to the code above.



You have to remove the ng-disabled on the submit button because we want the user to be able to click submit even if the form is not fully validated.



You have to add a variable after the form has been submitted. In your SubmitForm () function, just add $scope. Submitted = true;. Once the form is submitted, it saves the submitted variable with the commit value of true.



Adjust error rules from ng-class= "{' Has-error ': userform.name. $invalid &&!userform.name. $pristine}" to ng-class= "{" Has-error ': userform.name. $invalid &&!userform.name. $pristine && submitted} ". This ensures that the error message is displayed only when the form is submitted. You may need to adjust all the other ng-class and ng-show for this variable.



The error message is now displayed only if the submitted variable is set to True.



Error messages appear only when you click outside the input box



An error message (also known as losing focus Blur) is displayed only when you click outside the input box, which is more complicated than validating at commit. Validating the form requires a custom directive when the focus is lost. This is an instruction that allows you to manipulate the DOM.



We are writing an article devoted to this topic. At the same time, there are other resources that discuss creating custom directives to handle lost 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



All done



Now once we have filled in all the information correctly, our form Submit button will be available. Once we have submitted the form, we will see the pop-up message we set up.



With a few lines, we can:



Make input Box validation



Show form error messages



Customizing style classes



Automatically disable and enable forms



Custom Rules



As you can see, we use the angular built-in form validation technology to create a client-side validation form.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.