Almost all the web application has forms for receiving the data from the user. It allows the users to type in and the data will be processed in the backend. In AngularJS the forms will be synchronized to its model with the two-way data binding in angularjs through the ngModel directive. Lets see how AngularJS can benefit us when working with forms, especially during validation and various states of the forms.
AngularJS Form Validation Example
Lets take a simple login form example and see how we can add validation to it.
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>AngularJS Form Validation Example</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"> </script> </head> <body ng-app="myApp"> <div ng-controller="LoginCtrl"> <script type="text/javascript"> angular.module('myApp', []).controller('LoginCtrl', function($scope) { $scope.login = function(username,password) { if(username == 'Java' && password == 'InterviewPoint') { alert("Correct User"); } else { alert("Invalid User"); } }; }); </script> <form name="loginform"> <label>UserName :</label> <input type="text" ng-model="username" placeholder="Enter your User Name" required ng-minlength="5" /></br> </br> <label>Password :</label> <input type="text" ng-model="password" placeholder="Enter your Password" required /></br> </br> <button ng-click="login(username,password)" ng-disabled="loginform.$invalid">Login</button> </form> </div> </body> </html>
How things work here ?
- we have added a simple form, for which we have given the name as “loginform”
- Added HTML5 Validation tag “required” to each input fields to make it mandatory
- We have added a validator ng-minlength, which enforces that the minimum length of the value in the input field for the username is 5 characters
- To the submit button we have added the directive ng-disabled. This disables the submit button when the condition is satisfied. In our case we the “Login” button will be disabled when the form “loginform” is $invalid.
Output :
Hit on the URL : http://localhost:8080/AngularJS_Tutorial/LoginForm.html
You could see that the “Login” button will be disabled until the form validations are cleared. (i.e) a valid username is entered as it is a mandatory field and the length should be greater than 5 characters and password is entered as it is also a required field.
Form State in AngularJS
AngularJS has the below 5 form states
Form State | Description |
---|---|
$invalid | AngularJS sets this state when any of the validations like requried, ng-minlength, ng-maxlength etc on the any of the fields on the form is invalid |
$valid | This is inverse of $invalid state, this state is set when all the validation in the form is evaluation to correct |
$pristine | All forms in angularjs starts with this state, this state tells us the fields which is not modified by the user |
$dirty | $dirty is inverse of $pristine, it tells the user has modified the form element |
$error | This state contains all errors on each form element |
All the states mentioned above except $error are boolean and can be used as condition to show, hide, disable or enable any form element.
Displaying Error Message
Using the validators we can of-course enable or disable submit button but it doesn’t serve the purpose. We need to tell the user what went wrong and what has to be fixed.
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>AngularJS Form Validation Example</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"> </script> </head> <body ng-app="myApp"> <div ng-controller="LoginCtrl"> <script type="text/javascript"> angular.module('myApp', []).controller('LoginCtrl', function($scope) { $scope.login = function(username,password) { if(username == 'Java' && password == 'InterviewPoint') { alert("Correct User"); } else { alert("Invalid User"); } }; }); </script> <form name="loginform"> <label>UserName :</label> <input type="text" name="uname" ng-model="username" placeholder="Enter your User Name" required ng-minlength="5" /></br> <span style="color:red" ng-show="loginform.uname.$error.required">Username has to be entered</span> <span style="color:red"ng-show="loginform.uname.$error.minlength">Username has to be minimum 5 Character length</span> </br> <label>Password :</label> <input type="text" name="pwd" ng-model="password" placeholder="Enter your Password" required /></br> <span style="color:red" ng-show="loginform.pwd.$error.required">Password has to entered</span> </br> <button ng-click="login(username,password)" ng-disabled="loginform.$invalid">Login</button> </form> </div> </body> </html>
What are the changes made ?
- First we have added the name attribute to the input fields, “uname” for username textbox and “pwd” for password textbox. When we add a name to any input, it creates a model on the form for that particular input, with the error state.
- So now we can access the errors which occured in the username field by using “loginform.uname.$error.required” when the username is not entered and “loginform.uname.$error.minlength” when the minimum length criteria is not satisfied. Similarly for Password field “loginform.pwd.$error.required” when the password is not entered.
AngularJS Form Validation with ngMessages
In the above code we have added the ng-show directive to each of the field to display the error message. Before the release of ngMessages developers has to rely on the ng-show directive to display the error message. ngMessages is bundled in AngularJS 1.3 release, ngMessages added enhanced support for displaying messages to the user especially error messages during form validation.
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>AngularJS Form Validation Example</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.js"></script> </head> <body ng-app="myApp"> <div ng-controller="LoginCtrl"> <script type="text/javascript"> angular.module('myApp', ['ngMessages']).controller('LoginCtrl',function($scope) { $scope.login = function(username,password) { if(username == 'Java' && password == 'InterviewPoint') { alert("Correct User"); } else { alert("Invalid User"); } }; }); </script> <form name="loginform"> <label>UserName :</label> <input type="text" name="uname" ng-model="username" placeholder="Enter your User Name" required ng-minlength="5" /></br> <div ng-messages="loginform.uname.$error"> <div style="color:red" ng-message="required">Username has to be entered..</div> <div style="color:red" ng-message="minlength">Username has to be minimum 5 Character length..</div> </div> </br> <label>Password :</label> <input type="text" name="pwd" ng-model="password" placeholder="Enter your Password" required /></br> <div ng-messages="loginform.pwd.$error"> <div style="color:red" ng-message="required">Password has to be entered..</div> </div> </br> <button ng-click="login(username,password)" ng-disabled="loginform.$invalid">Login</button> </form> </div> </body> </html>
What are the changes made ?
- ngMessages will be bundled in a seperate js “angular-messages.js” we have included that as a first step.
- In order to use ngMessages module we need to include it as our module dependency, which we have added in our angular.module
- Thats all ngMessages will handle showing and hiding specific messages based on the errors. Basically ngMessages loops through the form fields errors, loginform.uname.$error for our username and loginform.pwd.$error for our password field.
- input type “name” field can basically have only 3 validations required, minlength, maxlength and those were mentioned in the ng-message attribute with the corresponding validation message.
Output :
Leave a Reply