AngularJS - SPLessons

AngularJS Validation

Chapter 21

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Validation

AngularJS Validation

shape Description

AngularJS Validation directives works on client-side forms to validate the form fields without any third party plugins. AngularJS checks the state of the form and input fields and lets users know about the current state.

To validate input, developers can either use standard HTML5 attributes or create own validation functions. Validation of form fields is done by AngularJS before copying their value into the $scope object properties for which the form fields are bound. Form field value is not copied into the $scope object property, if a form field is invalid. Instead, the respective $scope property is cleared. This is done to make sure that the $scope property does not contain any invalid values. Here, we will explain about different types of form validating directives:

shape Conceptual
figure

ng-minlength: and ng-maxlength:

shape Description

The ng-minlength and ng-maxlength form validation directives validates the data length given in a form field.

<div ng-controller="SPController" >
	<form>	 	
		<input type="text" id="name" ng-model="spForm.name" ng-minlength="6" ng-maxlength="12"> Name 	 	 
	</form>	 	
<div>	 	

ng-required:

shape Description

The ng-required directive checks whether form field value is null or not. Even used, the required attribute of AngularJS and HTML5 detects it automatically.

<input type="text" id="name" ng-model="spForm.name" ng-required="true"> Name

ng-pattern:

shape Description

To validate the input field value against a standard expression, ng-pattern directive is used.

<input type="text" id="name" ng-model="myForm.name" ng-pattern="/^\d+$/"> Name 

Checking Field Validation State

shape Description

AngularJS is constantly updating the state of both the form and input fields. The following can be used to detect an error:

  • $pristine
  • $dirty
  • $valid
  • $invalid

shape Example

<form name="spForm" ng-submit="spForm.submitForm()" >
 ...	
</form>	 	

From the above example, the name attribute of a form is spForm, which needs to be added to the $scope object as a property and can be accessed by corresponding controller function.


$scope.spForm

The below example shows how to access the form fields inside the form using $scope object in corresponding controller function.

<form name="myFormNg" ng-submit="spForm.submitForm()" >
	<input name="firstName" type="text" ng-model="spForm.firstName">	 	 
</form>	 

Syntax for how to access the firstName input field is as follows:


$scope.spForm.firstName

shape Properties

Property Description
$pristine If the form has not been altered, it returns ‘True’, otherwise returns ‘False’.
$dirty $dirty is opposite to $pristine – If the form has not been altered, it returns ‘False’. otherwise it returns ‘True’.
$valid If all the form fields are valid, it returns ‘True’, otherwise it returns ‘False’.
$invalid $invalid is opposite of the $valid– ‘False’, if the field (or all form fields) is valid, ‘True’ if the field (or a single field in the for) is invalid.

index.html

<!DOCTYPE html>
<html>

  <head>
    <title>AngularJS Form Validation</title>
    <script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="App.js"></script>
    <script src="Controller.js"></script>
  </head>

  <body>
    <h1>AngularJS Form Validation</h1>
    <div>
      <form ng-app="spApp" ng-controller="SPController" name="myForm" novalidate="">
        <label for="text">Text:</label>
        <input id="text" type="text" name="textValue" ng-model="textValue" required="" />
        <span style="color:red" ng-show="myForm.textValue.$dirty && myForm.textValue.$invalid">
          <span ng-show="myForm.textValue.$error.required">textValue is required.</span>
        </span>
        <br />
        <br />
        <label for="email">E-mail:</label>
        <input id="email" type="email" name="emailValue" ng-model="emailValue" required="" />
        <span style="color:red" ng-show="myForm.emailValue.$dirty && myForm.emailValue.$invalid">
          <span ng-show="myForm.emailValue.$error.required">Email is required.</span>
          <span ng-show="myForm.emailValue.$error.email">Invalid email address.</span>
        </span>
        <br />
        <br />
        <input type="submit" ng-disabled="myForm.textValue.$dirty && myForm.textValue.$invalid ||  
myForm.emailValue.$dirty && myForm.emailValue.$invalid " />
      </form>
    </div>
  </body>

</html>

Controller.js

myApp.controller("SPController", function($scope) {
       $scope.textValue="Smith Watson";
  });

App.js

var myApp = angular.module('spApp', []);
label
    {
      width: 80px;
      display: inline-block;
      vertical-align: middle;
    }

    input
    {
      width: 150px;
      vertical-align: middle;
    }

    textarea
    {
      width: 150px;
      height: 100px;
      vertical-align: middle;
    }

    .valueItems
    {
      display: inline-block;
      vertical-align: middle;
    }

Output:

Summary

shape Key Points

  • AngularJS Validation is done on the fields of the form before copying their values into the $scope object properties.
  • ng-minlength, ng-maxlength, ng-required and ng-pattern are the types of form validating directives.
  • $pristine, $dirty, $valid and $invalid are used to check the form validation state.