Now days angularjs is the good front-end framework. In this post i will explain how to validate a form using angularjs. Lets create a sinple form and validate using angularjs.
Angular js text box validation using $touched and used ng-show
directive to only show the error message. Include angularjs file within head tag of your page. Copy below angularjs file and add in your page.
I have used $touched directive to validate the textbox. Now create a index.html file and copy paste below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
< !DOCTYPE html> <html> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"/> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body ng-app=""> <div class="container"> <h1 class="text-center">How to validate a form using angularjs</h1> <h3 class="text-center">Try leaving the input field blank:</h3> <form name="myForm" class="form-horizontal"> <p>Name: <input name="myName" class="form-control" ng-model="myName" required/> <span style="color: red;" ng-show="myForm.myName.$touched && myForm.myName.$invalid">Please enter the name.</span> </p> <p>Email: <input name="email" class="form-control" ng-model="email" required/> <span style="color: red;" ng-show="myForm.email.$touched && myForm.email.$invalid">Please enter the email.</span> </p> <p>Address: <input name="myAddress" class="form-control" ng-model="myAddress" required/> <span style="color: red;" ng-show="myForm.myAddress.$touched && myForm.myAddress.$invalid">Please enter the address.</span> </p> </form> </div> </body> </html> |
See the live demo and then download the complete code from below link.
Live demo Download
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: angular bootstrap form, angularjs email validation, angularjs form, angularjs form validation, form validation, form validation angularjs