Client Side Form Validation in AngularJS

Introduction

In this article, we will demonstrate how to validate inputs in AngularJS, AngularJS provides states of form and input fields, which are can be used to show validation messages.

Getting Started

AngularJS provided client-side form validation, where we can apply validation before sending requests to the server. AngularJS provides some properties which represent the state of form and input fields. For example, AngularJS provides a $touched state to know whether the input field has touched or not.

AngularJS remembers each and every state of form and input fields and immediately notifies to view if state changes. For example, let's discuss $touched state when the form loads the first time and you have not touched any field then by default its value is false, and when touched it becomes true.

Using AngularJS form and input states you can display validation messages in the form and you can restricts as well. For example

 <span ng-show="schoolForm.ShortName.$touched && schoolForm.ShortName.$error.required"> Enter short name.</span><  

Above example display field required message when field $error.required becomes true, if you try to submit form without entering any value in the name field.

Example of accessing state properties

 <FormName>.<AngularProperty>  
 <FormName>.<InputFieldName>.<AngularProperty>  

Below is the list of state that form have

  1. $pristine:No fields have been modified yet
  2. $dirty:One or more have been modified
  3. $invalid:the form content is not valid
  4. $valid:the form content is valid
  5. $submittedthe form is submitted

Below is the list of state that input field have

  1. $touched:1.The field has been touched
  2. $pristine:The field has not been modified yet
  3. $dirty:The field has been modified
  4. $invalid:4.The field content is not valid
  5. $valid:The field content is valid
AngularJS also provides classes on the form and its inputs so that you can style each state accordingly. AngularJS provides ng-class which allows to add classes based on an expression.

AngularJS provides a basic implementation for most common HTML5 input types as well as some directives for validation. AngularJS provides below directives for form validation

Param Type Details
ngModel string Assignable AngularJS expression to data-bind to.
name
(optional)
string Property name of the form under which the control is published.
required
(optional)
string Sets required validation error key if the value is not entered.
ngRequired
(optional)
boolean Sets required attribute if set to true
ngMinlength(optional) number Sets minlength validation error key if the value is shorter than minlength.
ngMaxlength
(optional)
number Sets maxlength validation error key if the value is longer than maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any length.
ngPattern
(optional)
string Sets pattern validation error key if the ngModel $viewValue value does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For instance, "abc" will be converted to new RegExp('^abc$').
Note: Avoid using the g flag on the RegExp, as it will cause each successive search to start at the index of the last search's match, thus not taking the whole input value into account.

ngChange
(optional)
string AngularJS expression to be executed when input changes due to user interaction with the input element.

ngTrim
(optional)
boolean If set to false AngularJS will not automatically trim the input. This parameter is ignored for input[type=password] controls, which will never trim the input.(default: true)
It is good practice while handling validation in AngularJS that override default HTML5 validation rule as it will look pretty ugly. To override default HTML5 validation we need to use novalidate directive.

Go through with the below example, to get more ideas for implementation form validation in AngularJS.
Example:
This example demonstrates to create and update school details, this example implements form validation and if form is valid then form allows user to submit details.
Module
 //declare module  
 var schoolapp=angular.module("schoolapp",[]);  
  schoolapp.controller("schoolcont",function($scope,$http){  
 $scope.school={Code:0,ID:0,Name:'',ShortName:'',URL:''};  
 $scope.school.Name="Kailash";  
  $scope.schools=[];  
  $scope.getschool=function(){   
  $http.get("https://www.google.co.in/")   
   .then(function(response) {   
   alert(response.status);   
    $scope.students = response.data;   
   }  
    ,function errorCallback(response){   
     alert('Error Code:'+response.status+',Message:'+response.statusText);   
    });   
    }  
       //function for adding or updating school details  
        $scope.updateschool=function(){  
      $http.get("https://www.sms/updateschool")   
   .then(function(response) {   
   alert(response.status);   
    $scope.pg = response.data;   
   }   
    ,function errorCallback(response){   
     alert('Error Code:'+response.status+',Message:'+response.statusText);   
    });   
    }   
        //function for clear input values  
       $scope.clear=function()  
       {  
            $scope.school.Code=0;  
            $scope.school.ID=0;  
            $scope.school.Name="";  
            $scope.school.ShortName="";  
             $scope.school.URL="";  
       }  
  });   
View
 <HTML ng-app = "schoolapp">    
 <HEAD>  
  <TITLE>AngularJS: School Window</TITLE>   
  <script src="E:\Projects\SchoolManagement\UI\Common\System\angular.min.js"></script>  
  <script src="E:\Projects\SchoolManagement\UI\Modules\SchoolModule.js"></script>  
  </HEAD>  
 <BODY ng-controller="schoolcont">   
 <form name="schoolForm" novalidate>   
     <P>   
     <TABLE>   
     <TR>   
     <TD>Name:</TD>   
     <TD>  
        <INPUT TYPE="txt" name="Name" ng-model="school.Name" required/>  
        <br />  
    <span ng-show="schoolForm.Name.$touched && schoolForm.Name.$error.required">Enter school name.</span>  
      </TD>   
     </TR>   
     <TR>   
     <TD>Short Name:</TD>   
     <TD>  
           <INPUT TYPE="txt" name="ShortName" ng-model="school.ShortName" required/> <br />  
            <span ng-show="schoolForm.ShortName.$touched && schoolForm.ShortName.$error.required"> Enter short name.</span></TD>    
     </TR>   
     <TR>   
     <TD>URL:</TD>   
     <TD><INPUT TYPE="txt" name="url" ng-model="school.URL" required/>  
            <br />  
            <span ng-show="schoolForm.url.$touched && schoolForm.url.$error.required">URL is required.</span></TD>   
            </TD>   
     </TR>    
     <TR>   
     <TD>   
     </TD>   
     <TD>   
      <button type="submit" ng-click="updateschool()" ng-disabled="schoolForm.$invalid" >Save</button>  
           <button type="submit" ng-click="updateschool()" ng-disabled="schoolForm.$invalid" >Save &Next</button>             
     <button ng-click="clear()">Clear</button>   
     </TD>   
     </TR>   
     </TABLE>   
 </form>  
     <HR/>   
     <table border="1">    
      <tr>    
       <th>ID</th>    
       <TD>Name:</TD>   
        <TD>Short Name:</TD>   
       <TD>URL:</TD>    
       <th>Action</th>   
      </tr>    
      <tr ng-repeat="school in schools | filter:searchText">   
                <td>{{schools.ID}}</td>              
       <td>{{schools.Name}}</td>    
       <td>{{schools.ShortName}}</td>    
       <td>{{schools.URL}}</td>    
       <TD>   
                     <button ng-click="edit(school)">Edit</button>    
                     <button ng-click="delete(school)">Delete</button>    
                </TD>   
      </tr>    
     </table>    
          </P>   
   </BODY>    
  </HTML>    

Summary

Hope this article, helps you to get idea about AngularJS client side form validation. Happy coding and enjoy.

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال