Client Side Form Validation in AngularJS

Client-side form validation in AngularJS is an essential feature that ensures user input is validated on the client side before sending it to the server. AngularJS provides built-in directives to make form validation straightforward. These directives allow you to add validations to form fields, such as ng-required, ng-minlength, ng-pattern, etc., and show error messages when the form is not filled out correctly.

Here’s a step-by-step guide to implementing client-side form validation in AngularJS:

Form Validation in AngularJS

Form Validation in AngularJS


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 restricts to send form request to server.

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.

Form and Input Field State Properties

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

Example of accessing state properties

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

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.

Example of Input Validation

You can add different types of form fields with AngularJS validation directives. Here are a few examples:

a. Required Field Validation

 <label for="name">Name:</label>  
 <input type="text" id="name" name="name" ng-model="user.name" ng-required="true" />  
 <span ng-show="userForm.name.$error.required && userForm.name.$touched">Name is required.</span>  

b. Email Validation

 <label for="email">Email:</label>  
 <input type="email" id="email" name="email" ng-model="user.email" ng-required="true" />  
 <span ng-show="userForm.email.$error.required && userForm.email.$touched">Email is required.</span>  
 <span ng-show="userForm.email.$error.email && userForm.email.$touched">Invalid email format.</span>  

c. Minimum Length Validation

 <label for="password">Password:</label>  
 <input type="password" id="password" name="password" ng-model="user.password" ng-required="true" ng-minlength="6" />  
 <span ng-show="userForm.password.$error.required && userForm.password.$touched">Password is required.</span>  
 <span ng-show="userForm.password.$error.minlength && userForm.password.$touched">Password must be at least 6 characters.</span>  

d. Pattern Validation (For custom patterns)

 <label for="phone">Phone:</label>  
 <input type="text" id="phone" name="phone" ng-model="user.phone" ng-pattern="/^\d{10}$/" ng-required="true" />  
 <span ng-show="userForm.phone.$error.required && userForm.phone.$touched">Phone number is required.</span>  
 <span ng-show="userForm.phone.$error.pattern && userForm.phone.$touched">Invalid phone number (10 digits required).</span>  

Display Error Messages

AngularJS provides built-in form control objects to display error messages. These objects are accessible in the form using formControlName.$error, where formControlName is the name of the form input element.

Here’s an example of how you can show error messages for multiple fields:

 <form name="userForm" ng-submit="submitForm(userForm)" novalidate>  
  <label for="name">Name:</label>  
  <input type="text" id="name" name="name" ng-model="user.name" ng-required="true" />  
  <span ng-show="userForm.name.$error.required && userForm.name.$touched">Name is required.</span>  
  <label for="email">Email:</label>  
  <input type="email" id="email" name="email" ng-model="user.email" ng-required="true" />  
  <span ng-show="userForm.email.$error.required && userForm.email.$touched">Email is required.</span>  
  <span ng-show="userForm.email.$error.email && userForm.email.$touched">Invalid email format.</span>  
  <label for="password">Password:</label>  
  <input type="password" id="password" name="password" ng-model="user.password" ng-required="true" ng-minlength="6" />  
  <span ng-show="userForm.password.$error.required && userForm.password.$touched">Password is required.</span>  
  <span ng-show="userForm.password.$error.minlength && userForm.password.$touched">Password must be at least 6 characters.</span>  
  <button type="submit" ng-disabled="userForm.$invalid">Submit</button>  
 </form>  

Custom Validation (Optional)

You can also create your own custom validators in AngularJS. Here's an example of a custom validator that checks if a username is available:

 angular.module('myApp', [])  
  .controller('FormController', function($scope) {  
   $scope.submitForm = function(form) {  
    if (form.$valid) {  
     alert("Form submitted successfully!");  
    } else {  
     alert("Please fill out the form correctly.");  
    }  
   };  
   $scope.usernameAvailable = function(username) {  
    // Mocked API call  
    var availableUsernames = ['admin', 'guest', 'superuser'];  
    return availableUsernames.indexOf(username) === -1;  
   };  
  });  

And in your HTML form:

 <label for="username">Username:</label>  
 <input type="text" id="username" name="username" ng-model="user.username" ng-required="true" ng-pattern="/^[a-zA-Z0-9_]+$/" />  
 <span ng-show="userForm.username.$error.required && userForm.username.$touched">Username is required.</span>  
 <span ng-show="userForm.username.$error.pattern && userForm.username.$touched">Invalid username format.</span>  
 <span ng-show="userForm.username.$error.usernameAvailable && userForm.username.$touched">Username is taken.</span>  

To implement this custom validation, you would need to use a custom AngularJS validator directive, but this is a more advanced step.

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

AngularJS provides an efficient way to handle client-side form validation. By combining built-in directives such as ng-required, ng-minlength, and ng-pattern, you can ensure that your forms are validated properly before submission. Additionally, you can create custom validators to meet specific requirements.

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

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