Working With AngularJS Form

Introduction

As a web developer creating a form is a very common task for us. AngularJS enhances the user experience and validation. AngularJS makes two-way binding easy, in other words bind data from a model object ($scope) to form an input control and vice-versa.

In the following example we have created a simple form with one field and bound it with User.firstName.

  1. <body ng-app="myapp">    
  2.     <div ng-controller="MyFromController" >    
  3.         <form>    
  4.             <table border="1px solid">    
  5.                 <tr>    
  6.                     <td>First name :</td>    
  7.                     <td>    
  8.                         <input type="text" name="firstName" ng-model="User.firstName">    
  9.                         </td>    
  10.                     </tr>    
  11.                 </table>    
  12.             </form>    
  13.             <div>    
  14.                Hello {{User.firstName}} !!!    
  15.             </div>    
  16.      </div>    
  17.         <script>    
  18.             angular.module("myapp", [])    
  19.             .controller("MyFromController", function ($scope)
  20.             {    
  21.                $scope.User = {};    
  22.                $scope.User.firstName = "Ratnesh";    
  23.             });    
  24.        </script>    
  25. </body>   
Now we will add some more fields of various types to our form to enter employee details. Here we have added a radio for gender as:
  1. <input type="radio" ng-model="User.Gender" value="Male">Male    
  2. <input type="radio" ng-model="User.Gender" value="Female">Female   
One select box for “position” as:
  1. <select ng-model="User.Position" ng-options="obj.id as obj.name for obj in Positions">    
  2.     <option value="">--Select--</option>    
  3. </select> 
One Multi select box for Languages as:
  1. <select multiple="true" ng-model="User.Languages" ng-options="obj.id as obj.name for obj in Languages"></select> 
We have also added some input fields for Age, email and so on. We will use them to understand the validation later in this article. So our form looks such as:



Validation


AngularJS comes with a set of validation directives. It validates the form's control value before assigning to the $scope properties. If any control's value is invalid, it is not assigned into the $scope and the corresponding $scope property is cleared.

Some of the validation directives that we will use in our employee details page are as follows.
  • ng-minlength to validate the length of the data entered
  • ng-maxlength to validate the length of the data entered
  • ng-pattern to validate the value of an input field against a regular expression
  • ng-required to make a field requuired
We have set our validation rule for each control. So our HTML file would look as:
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>    
  5.     <style type="text/css">    
  6.        table.myTable { border-collapse:collapse; }    
  7.        table.myTable td, table.myTable th { border:1px solid black;padding:2px; }    
  8.      </style>    
  9. </head>    
  10. <body ng-app="myapp">    
  11.     <div ng-controller="MyFromController" >    
  12.         <form>    
  13.             <table class="myTable">    
  14.                 <tr>    
  15.                     <td colspan=3>    
  16.                         <h3>Employee Details</h3>    
  17.                     </td>    
  18.                 </tr>    
  19.                 <tr>    
  20.                     <td>Emp ID :</td>    
  21.                     <td>    
  22.                         <input name="EmployeeID" ng-model="User.EmpID" required="">    
  23.                         </td>    
  24.                         <td></td>    
  25.                     </tr>    
  26.                     <tr>    
  27.                         <td>First name :</td>    
  28.                         <td>    
  29.                             <input type="text" name="firstName" ng-model="User.firstName" required ng-minlength="5" ng-maxlength="8">    
  30.                             </td>    
  31.                             <td></td>    
  32.                         </tr>    
  33.                         <tr>    
  34.                             <td>Last name :</td>    
  35.                             <td>    
  36.                                 <input type="text" name="lastName" ng-model="User.lastName" ng-minlength="5" ng-maxlength="8">    
  37.                                 </td>    
  38.                                 <td></td>    
  39.                             </tr>    
  40.                             <tr>    
  41.                                 <td>Age :</td>    
  42.                                 <td>    
  43.                                     <input type="text" name="age" ng-model="user.age" type="number"/>    
  44.                                 </td>    
  45.                                 <td></td>    
  46.                             </tr>    
  47.                             <tr>    
  48.                                 <td>E-mail :</td>    
  49.                                 <td>    
  50.                                     <input name="email" ng-model="User.Email" type="email">    
  51.                                     </td>    
  52.                                     <td></td>    
  53.                                 </tr>    
  54.                                 <tr>    
  55.                                     <td>Gender :</td>    
  56.                                     <td>    
  57.                                         <input type="radio" ng-model="User.Gender" value="Male" >Male    
  58.                                                <input type="radio" ng-model="User.Gender" value="Female">Female    
  59.                                                </td>    
  60.                                             <td></td>    
  61.                                         </tr>    
  62.                                         <tr>    
  63.                                             <td>Position :</td>    
  64.                                             <td>    
  65.                                                 <select ng-model="User.Position" ng-options="obj.id as obj.name for obj in Positions">    
  66.                                                     <option value="">--Select--</option>    
  67.                                                 </select>    
  68.                                             </td>    
  69.                                             <td></td>    
  70.                                         </tr>    
  71.                                         <tr>    
  72.                                             <td>Languages :</td>    
  73.                                             <td>    
  74.                                                 <select multiple="true" ng-model="User.Languages" ng-options="obj.id as obj.name for obj in Languages"></select>    
  75.                                             </td>    
  76.                                             <td></td>    
  77.                                         </tr>    
  78.                                         <tr>    
  79.                                             <td></td>    
  80.                                             <td></td>    
  81.                                             <td>    
  82.                                                 <input type="submit" ng-click="update(User)" value="Save" />    
  83.                                             </td>    
  84.                                         </tr>    
  85.                                     </table>    
  86.                                 </form>    
  87.                             </div>    
  88.                             <script>    
  89.                                 angular.module("myapp", [])    
  90.                 .controller("MyFromController", function ($scope) {    
  91.                 $scope.User = {};    
  92.                 $scope.Positions = [    
  93.                 { id: "1", name: "Developer" }    
  94.                 , { id: "2", name: "Team Lead" }    
  95.                 , { id: "3", name: "Project Manager" }    
  96.                 ];    
  97.                 $scope.Languages = [    
  98.                 { id: "1", name: "C#" }    
  99.                 , { id: "2", name: "Vb.Net" }    
  100.                 , { id: "3", name: "Java" }    
  101.                 ];    
  102.     
  103.                 $scope.update = function (user) {    
  104.                 alert(JSON.stringify(user));    
  105.                 };    
  106.     
  107.     
  108.                 });    
  109.                 </script>    
  110. </body>    
  111. </html>  
If we submit our form with all valid values then we would get an alert that shows all the values in a JSON string as:





Now change the values for some field as invalid and submit as in the following:





We can see that all the invalid values and properties have been removed from the user object by Angular. Until now we have not shown any message to our form user about validation. For this we need to use form and control state. If we had added a name attribute to our form then it would be added to $scope as a property. In our case we would add “EmpForm” as name. Now we access the model property with the form name. For example we can access the firstName as:
  1. $scope.EmpForm.firstName 
We have changed the form tag as:
  1. <form name="EmpForm" ng-submit="submit()" novalidate> 
And defined a submit as:
  1. $scope.submit = function() { $scope.submitted = true; };  
We have written some code to show a custom message for first name as follows:
  1. <tr>  
  2.     <td>First name :</td>  
  3.     <td>  
  4.         <input type="text" name="firstName" ng-model="User.firstName" required ng-minlength="5" ng-maxlength="8">  
  5.     </td>  
  6.     <td>  
  7.         <span ng-if="submitted">  
  8.             <span ng-if="EmpForm.firstName.$error.required">Required</span>  
  9.             <span ng-if="EmpForm.firstName.$error.minlength">should be more than 5</span>  
  10.             <span ng-if="EmpForm.firstName.$error.maxlength">should be less than 8</span>  
  11.         </span>  
  12.     </td>  
  13. </tr> 
This code will show a message as “Required” if the user submits the form with a blank first name. If the user violates length in either side then he would get a different message.


Similar Articles