Differentiation of AngularJS Form Validation

If you are interested to learn about the AngularJS Forms

AngularJS can validate input data.

Form Validation

AngularJS offers client-side form validation. AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also holds information about whether they have been touched, or modified, or not. You can use standard HTML5 attributes to validate input, or you can make your own validation functions. Client-side validation cannot alone secure user input. Server side validation is also necessary.

Required

Use the HTML5 attribute required to specify that the input field must be filled out:

Example

The input field is required:

<form name="myForm">
  <input name="myInput" ng-model="myInput" required>
</form>

The input's valid state is:
{{myForm.myInput.$valid}}

E-mail

Use the HTML5 type email to specify that the value must be an e-mail:

Example

The input field has to be an e-mail:

<form name="myForm">
  <input name="myInput" ng-model="myInput" type="email">
</form>

<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>

Form State and Input State

AngularJS is constantly updating the state of both the form and the input fields.

Input fields have the following states:

  • $untouched The field has not been touched yet
  • $touched The field has been touched
  • $pristine The field has not been modified yet
  • $dirty The field has been modified
  • $invalid The field content is not valid
  • $valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

  • $pristine No fields have been modified yet
  • $dirty One or more have been modified
  • $invalid The form content is not valid
  • $valid The form content is valid
  • $submitted The form is submitted

They are all properties of the form, and are either true or false. You can use these states to show meaningful messages to the user. Example, if a field is required, and the user leaves it blank, you should give the user a warning:

Example

Show an error message if the field has been touched AND is empty:

<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span>

CSS Classes

AngularJS adds CSS classes to forms and input fields depending on their states. The following classes are added to, or removed from, input fields:

  • ng-untouched The field has not been touched yet
  • ng-touched The field has been touched
  • ng-pristine The field has not been  modified yet
  • ng-dirty The field has been modified
  • ng-valid The field content is valid
  • ng-invalid The field content is not valid
  • ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
  • ng-invalid-key Example: ng-invalid-required

The following classes are added to, or removed from, forms:

  • ng-pristine No fields has not been modified yet
  • ng-dirty One or more fields has been modified
  • ng-valid The form content is valid
  • ng-invalid The form content is not valid
  • ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
  • ng-invalid-key Example: ng-invalid-required

The classes are removed if the value they represent is false. Add styles for these classes to give your application a better and more intuitive user interface.

Example

<style>
input.ng-invalid {
  background-color: pink;
}
input.ng-valid {
  background-color: lightgreen;
}
</style>

Forms can also be styled:

Example

Apply styles for unmodified (pristine) forms, and for modified forms:

<style>
form.ng-pristine {
  background-color: lightblue;
}
form.ng-dirty {
  background-color: pink;
}
</style>

Custom Validation

To create your own validation function is a bit more tricky; You have to add a new directive to your application, and deal with the validation inside a function with certain specified arguments.

Example

Create your own directive, containing a custom validation function, and refer to it by using my-directive. The field will only be valid if the value contains the character “e”:

<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>

<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        if (value.indexOf("e") > -1) {
          mCtrl.$setValidity('charE', true);
        } else {
          mCtrl.$setValidity('charE', false);
        }
        return value;
      }
      mCtrl.$parsers.push(myValidation);
    }
 

Example Explained:

In HTML, the new directive will be referred to by using the attribute my-directive. In the JavaScript we start by adding a new directive named myDirective. Remember, when naming a directive, you must use a camel case name, myDirective, but when invoking it, you must use - separated name, my-directive.

Then, return an object where you specify that we require  ngModel, which is the ngModelController. Make a linking function which takes some arguments, where the fourth argument, mCtrl, is the ngModelController, Then specify a function, in this case named myValidation, which takes one argument, this argument is the value of the input element. Test if the value contains the letter “e”, and set the validity of the model controller to either true or false. At last, mCtrl.$parsers.push(myValidation); will add the myValidation function to an array of other functions, which will be executed every time the input value changes.

Validation Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
<body>

Validation Example

<form  ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>

Username:
  <input type="text" name="user" ng-model="user" required>
  <span style="color: red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm. user. $error. required">Username is required.</span>
  </span>

Email:
  <input type="email" name="email" ng-model="email" required>
  style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
   ng-show="myForm.email.$error.required">Email is required.
   ng-show="myForm.email.$error.email">Invalid email address.
  </span>

  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">


</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
  $scope.user = 'John Doe';
  $scope.email = 'john.doe@gmail.com';
})
</body>
</html>

The HTML form attribute novalidate is used to disable default browser validation.

Example Explained

The AngularJS directive ng-model binds the input elements to the model. The model object has two properties: user and email. Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and $invalid.

 AngularJS form Properties:

There are some properties of form in angular which is used to perform validation in form like $invalid$valid$dirty$pristine$touched. These are of the boolean type means return true or false when called. These properties will get called in different conditions.

     – $invalid: This property tells that the input which is entered is invalid.

     – $valid: This property tells that the input value is valid.

     – $dirty: This property tells that the form element is accessed.

     – $pristine: This property tells that the form element is not accessed yet.

Syntax of Properties:
To use property for validation, use the following syntax:

<formname>.<formelementname>.<propertyname>

Example:

form name="frm" novalidate>
input type="email" ng-model="user.email" name="email" placeholder="Enter Email Address" autocomplete="off" required>
span ng-show="frm.email.
$dirty  frm.email.$invalid">Email Address is not valid

Explaination: In the above example, we have used $invalid and $dirty properties. It means, if the value is entered and it is invalid for the form-element, then the message within span tag will show.

 Form Controls Parameters:

There are some form control parameters provided by angular to perform validation on form input controls.

<input
ng-model="string"

[name=”string”]

[required=”string”]

[ng-required=”boolean”]

[ng-minlength=”number”]

[ng-maxlength=”number”]

[ng-pattern=”string”]

[ng-change=”string”]

[ng-trim=”boolean”]

Example:

input type="text"
name="username"
ng-model="user.firstname"
placeholder="Enter First Name"
autocomplete="off"
span ng-show="frm.username.$dirty;
frm.username.$error.maxlength">maximum 10 charecters allowed

Note:- max-length and min-length are the keys of $error ( object hash containning reference to form and controls).

CSS Styling

There are some classes which will be automatically added by angular in the form-element according to the status of the input element.

     – ng-valid: Class added when the input is valid.

     – ng-invalid: Classadded when the input is invalid.

     – ng-dirty: Classadded when the form element is accessed.

     – ng-pristine: Classadded when the form element is not accessed yet.

     – ng-untouched: Class added when the form-element is not touched yet.

Explanation:  if an input box is empty a class ng-pristine will be automatically added but if the user entered something the ng-pristine class will be replaced by ng-dirty.

Creating an Application:

Let’s create a form and validate it using angular.

Requirement of form:

  • Name is required.
  • Email is required and it should be in the email format.
  • Password is required having minimum 5 and maximum 10 letters.
  • Message is required.
  • Gender must be selected.
  • Country must be selected.

First, add novalidate with the form to disable the html5 validation.

Note:- To use angular form validation, must disable the traditional HTML validation. For this, use nonvalidate validatation property in the form.

Also, use ng-disabled with the submit button to disable submit till all the values within the form control are valid. This file creates a form in which validation is applied.

<html>
<head>
<title>AngularJS Forms</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/angular.min.js"
<script type="text/javascript" src="js/app.js">
</head>
<body class="container">
<div class="row" ng-app="myApp" ng-controller="maincntrl">
<h2 class="text-center"> AngularJS - Form </h2>
<div class="col-md-offset-1 col-md-6 col-sm-12" >
<div class="login">
<h2>Registration Form</h2>
<!--Code of form started-->
<form class="form-horizontal" name="form" novalidate>
<!--Code to validate first name is written here-->
<div class="form-group" >
 id="label" class="control-label">First Name:
<input type="text" class="form-control" name="username" ng-model="user. first name" placeholder="Enter First Name" autocomplete="off" required 

<!--Code to validate email address is written here-->
<div class="form-group">
<label id="label" class="control-label">Email:</label>
<input type="email" class="form-control" ng-model="user .email" name="email" placeholder="Enter Email Address" autocomplete="off" required>
<span class="msg" ng-show="frm. email. $dirty && frm. email. $invalid">Email Address is not valid

<!--Code to validate password is written here-->
<div class="form-group">
<label id="label" class="control-label">Password:</label>
<input type="password" class="form-control" ng-model="user.pass" name="pass" placeholder="Enter Password" autocomplete="off" ng-minlength="5" ng-maxlength="12" required>
<span class="msg" ng-show="frm. pass. $dirty && frm. pass. $error. minlength">password must contain atleast 5 charecters</span>
<span class="msg" ng-show="frm. pass. $dirty && frm. pass. $error. maxlength">max-length of password reached</span>

<!--Code to validate message input box-->
<div class="form-group">
id="label" class="control-label">Message:
<text area type="text area" rows="2" cols="50" name="message" class="form-control" ng-model="user.message" placeholder="Enter Your Message" autocomplete="off" required></text area>
<span class="msg" ng-show="frm. message. $error. required">Enter a message</span>

<!--Code to validate gender field-->
<div class="form-group">
<label id="label" >Gender:</label>;
Male;<input type="radio" name="gender" ng-model="user .gender" value="male" required>
 Female <input type="radio" name="gender" ng-model="user .gender" value="female" required.
 class="msg" ng-show="frm. gender. $error. required">select any gender
<!--Code to validate country field-->
<div class="form-group"> 
id="label" class="control-label">Country
select class="form-control" ng-model="user. country" name="cont" required
value="india">India
value="USA">USA</option>
 value="switzerland">switzerland
</select>
<span class="msg" ng-show="frm.cont.$error.required"> Select a value</span>

<!--Code to disable submit button is written here-->
<div class="form-group">
<input ng-disabled="frm.$invalid" class="btn btn-warning" type="submit" ng-click="call()" value="Submit">

<!--code to show values after clicking pn submit button-->
<div class="col-md-offset-1 col-md-4 col-sm-12">
<div class="alert1" ng-show="submit_success" style="word-wrap:break-word;">
<div class="login" >
<h2>submitted values</h2>
<hr>
class="text-center">Submited Values:
<div class="row">
<div class="col-md-5 headname">
FirstName: <div class="col-md-7"> {{server.firstname}}
<div class="row"><div class="col-md-5 headname"> Email:  </div> <div class="col-md-7"> {{server.email}}
<div class="row"><div class="col-md-5 headname"> Password:</div><div class="col-md-7"> {{server.pass}}
div class="row"><div class="col-md-5 headname"> Message: </div><div class="col-md-7"> {{server.message}}
<div class="row"><div class="col-md-5 headname"> Gender:</div> <div class="col-md-7">{{server.gender}}
<div class="row"><div class="col-md-5 headname"> Country: </div><div class="col-md-7"> {{server.country}}
<b>JSON Data: </b> {{server}} 
JavaScript File: app.js

This file works after we click on submit button. It will retrieve and shows the submited values at the right side of form.

var myApp = angular. module("myApp", [])
myApp. controller("maincntrl", function ($scope) {
$scope.submit_success = false;
$scope.call = function () 
$scope.server = angular.copy($scope.user);
$scope.submit_success = true;
);

This file works after we click on submit button. It will retrieve and shows the submited values at the right side of form.

<code> var myApp = angular. module("myApp", []);
myApp. controller("main cntrl", function ($scope) 
$scope.submit_success = false;
$scope.call = function () {
$scope.server = angular. copy($scope.user);
$scope.submit_success = true;

It contains the styling CSS of the form.

import url(http://fonts.googleapis.com/css?family=Raleway);
h2{
margin-top:20px;
margin-bottom:20px;
}
.login h2{
background-color: #FEFFED;
text-align: center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}
.login hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 10px;
}
.login{
width:100%;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 10px;
word-wrap: break-word;
}
.login p{
margin-top:8px;
font-size:16px;
}
.login hr {
margin-bottom: 30px;
}
input[type=text]{
width:99.5%;
padding: 10px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}
label#label{
margin-bottom:10px;
font-size:18px;
font-weight:bold;
}
textarea.ng-invalid{
border:1px solid red;
border-left: 5px solid red;
}
textarea.ng-valid.ng-dirty{
border:1px solid green;
border-left: 5px solid green;
}
select.ng-invalid{
border:1px solid red;
border-left: 5px solid red;
}
select.ng-valid.ng-dirty{
border:1px solid green;
border-left: 5px solid green;
}
input.ng-invalid{
border:1px solid red;
border-left: 5px solid red;
}
input.ng-valid.ng-dirty{
border:1px solid green;
border-left: 5px solid green;
}
span.msg{
margin-top:15px;
color:red;
}
.headname{
font-size:15px;
}

Differentiation of AngularJS Form Validation
Show Buttons
Hide Buttons