Various Types of Form Validation in AngularJS

One of the coolest features of AngularJS is client-side validation. There are so many form directives available in AngularJS. We will talk about some of them here, we will also explain custom validation. Using it you can create your own validations.
 
Client-side form validation can be handled very easily using AngularJS without adding so much extra effort. To use form validation, first ensure that the form has a "name" associated with it as in the following:

<Form name="Form">  </Form>

Now I am showing you various types of validations in AngularJS.
 
Required
 
To validate that a form input is filled in, to use this type of validation; just add "required" to the input field.
 
Example

<form name="Form">
    <input type="text" required />

 </form>
 
Minimum Length
 
To validate that an input field is at least a number of characters. To use this type of validation just add the "ng-minlength" directive of AngularJS inside the input field.
 
Syntax: ng-minlength="{number}"
 
 Example
 

<form name="Form">

   <input type="text" ng-minlength=5 />

</form>
 
Maximum Length
 
To validate that an input field is less than or equal to the number of characters. To use this type of validation just add the "ng-maxlength" directive of AngularJS inside the input field.
 
Syntax: ng-maxlength="{number}"
 
Example
 

<form name="Form">

   <input type="text" ng-maxlength=50 />

</form>
 
Email
 
To validate an email address of an input field, just set the input type to "Email".
 
Example
 

<form name="Form">

   <input type="Email" name="Email" ng-model="user.Email"  />

</form>
 
Number

To validate that an input field has a number, just set the input type to "number".
 
Example
 

<form name="Form">

   <input type="number" name="number" ng-model="user.Age" />

</form>
 
Pattern Matching
 
This type of validation is based on regular expression pattern expression and also called regular expression validation. This validation checks that the value of an input field matches a specific regular expression pattern. For this we use the "ng-pattern" directive of AngularJS.
 
Syntax: ng-pattern="/PATTERN/" 
 
Example
 

<form name="Form">

      <input type="text" ng-pattern="/a-zA-Z/" />

      <input type="text" ng-pattern="/0-9/" /> 

      <input type="text" ng-pattern="/a-zA-Z0-9/" /> 

</form>
 
In the preceding example:
 
1st input field will only use a-z and A-Z characters, 
2nd input field will only use 0-9 characters, 
3rd input field will only use a-z,A-Z and 0-9 characters.
 
URL

To validate that an input field has an URL, set the input type to "URL".
 

<form name="Form">

    <input type="url" name="homepage" ng-model="user.google_url" /> 

</form>
 
Custom Validations
 
Using AngularJS we can add or create our own validation very easily or quickly by using directives of AngularJS. Now I am showing you a simple example of custom validation.
 
Step 1: Create a Java-Script file in which custom validation is defined.

var app = angular.module('myApp', []);

   app.controller('MainCtrl'function ($scope) {

   $scope.test = 'this is wrong';

   });

 

app.directive('regexValidate'function () {

   return {

   restrict: 'A',// restrict to an attribute type.

   require: 'ngModel',// element must have ng-model attribute.

   link: function (scope, elem, attr, ctrl) {

      // here

      //scope = parent scope

      // elem = element

      // attr = attributes on the element

      // ctrl = controller for ngModel.

   var flags = attr.regexValidateFlags || '';

   //get the regex flags from the regex-validate-flags="" attribute (optional) 

   var regex = new RegExp(attr.regexValidate, flags);// create the regex obj.

   ctrl.$parsers.unshift(function (value) { // add a parser that will process each time the value is

                                            // parsed into the model when the user updates it.

   var valid = regex.test(value); // test and set the validity after update. 

   ctrl.$setValidity('regexValidate', valid);

   return valid ? value : #ff0000;// if it's valid, return the value to the model,

                                    // otherwise return undefined. 

     });

 

   ctrl.$formatters.unshift(function (value) {

   // add a formatter that will process each time the value

   // is updated on the DOM element.

   ctrl.$setValidity('regexValidate', regex.test(value));

   return value; // return the value or nothing will be written to the DOM.

      });}

   };

}); 
 
Step 2: Now inside the HTML File you need to write code as follows:

 

<div ng-app="myApp">

    <div ng-controller="MainCtrl">

        <form name="myForm" ng-submit="doSomething()">

        <label>

            Must contain the word <strong>blah</strong> (case insensitive)

            <br />

            <!-- set up the input, make sure it:

            1. has ng-model

            2. has a name="" so we can reference it in the model.

            3. has regex-validate

            4. has regex-validate-flags (This is optional) -->

            <input type="text" placeholder="Enter text here" ng-model="test" name="test" regex-validate="\bblah\b"

                regex-validate-flags="i" />

        </label>

        <!-- set up some sort of output for validation

         the format here is: [formName].[fieldName].$error.[validationName]

         where validation name is determined by

         ctrl.$setValidity(validationName, true/false) in your

         custom directive.-->

        <span style="color: red" ng-show="myForm.test.$error.regexValidate">WRONG!</span>

        <div>

            <!-- for added measure, disable the submit if the form is $invalid -->

            <button type="submit" ng-disabled="myForm.$invalid">

                Submit</button>

        </form>

    </div>

</div>
 
Depending on the above HTML and JavaScript code the input field (test) must contain the word "blah".
 
This was all about Validation. In this article we have explained various types of form validations; they are:

  • Required Field Validation
  • Minimum Length Validation
  • Maximum Length Validation
  • Email Validation
  • Number Validation
  • URL Validation
  • Pattern Validation or Regular Expression Validation
  • Custom Validation


Similar Articles