PROGRAMS

Form Validation in AngularJS with Example

AngularJS provides client-side validation, where it gives a way of monitoring the input fields of a form and notifying the user about the error on validations. Form validation in AngularJS ensures that the input fields are validated at the browser ( also known as client-side or UI level). Angular Form can be validated using Angular provided Form states and input fields state or by using the HTML5 attributes. So let us see go through different ways of form validations. Go through Login implementation in AngularJS.

We are going to discuss two types of form validations here, the approach that is explained in this post is a simple one but it is not flexible. The second approach is using the ngMessages module. The ngMessages module provides enhanced support for displaying error messages within templates (when rendering message objects with key/value object). Follow the link for “Form Validation with ngMessages“.

HTML5 Attributes:

Required: Use the HTML5 attribute required to specify that the input field must be filled out. It can not empty.

Look at the example as below.

<input name="myInput" ng-model="myInput" required>

Email: Use the HTML5 type email to specify that the input value should be an email. An example is shown below.

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

Angular Form Properties:

Angular provides several properties on forms that help us to validate the form and its input fields. They provide information about the form or it’s input fields which is basically its current state.

The Angular Form Properties(state) are listed below.

Property Name Description
$valid This property tells that the form/input field value is valid. True/False.
$invalid This property tells that the form/input field value is invalid. True/False.
$pristine This boolean property tells that the form/input has not been used/modified yet.
$dirty This boolean property tells that the form/input has been used/modified.
$touched This boolean property says that input field is touched (applied only for input).
$untouched This boolean property says that input field is not touched yet (applied only for input).
$submitted This boolean property says that the form is submitted (applied only for form).

Classes:

Angular also provides classes in forms and input fields so that you can style each of them accordingly based on their state. These classes are similar to angular form properties as explained above.

Class Name Description
ng-valid The input filed content is valid.
ng-invalid The input filed content is not valid.
ng-pristine The form/ input field has not been modified/used yet.
ng-dirty The form/ input field has been modified/used.
ng-touched The input field has been touched.
ng-untouched The input field has not been touched yet.

 

How to access Form Properties in order to validate?

For Form: <form name>.<angular property>

For Input Field: <form name>.<input name>.<angular property>

 

Example for Form Validation in AngularJS:

Let us see an example of how to validate a form. We will take a simple login page. In this login page, we have three fields: Name, Username(should be an email of the user) and Password.

Our validation requirement for login form is as follows:

  1. Name field is required
  2. Name field length must be between 3 and 8.
  3. Username should be a valid email.
  4. The password should be in length between 6 and characters.

 

Please look at an example as shown below.

Folder structure includes 2 pages:  index.html and app.js. HTML is the main base shell which holds all the basic scripts required to run an app and the login form.

//Index.html
<!DOCTYPE html>
<html>
<head>
    <!-- CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/
3.0.3/css/bootstrap.min.css" />
    <!-- JS -->
    <script src="https://code.angularjs.org/1.4.0-rc.1/angular.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="validationApp" ng-controller="mainController">
<div class="container" style="width:600px">
    
    <!-- PAGE HEADER -->
    <div class="page-header"><h1>AngularJS Form Validation</h1></div>
   
    <!--======FORM ======-->
    
    <!-- pass in the variable if our form is valid or invalid -->
    <form name="loginForm" ng-submit="submitForm(loginForm.$valid)" novalidate>
        <!-- USERNAME -->
        <div class="form-group" ng-class="{ 'has-error' : 
             loginForm.name.$invalid && !loginForm.name.$pristine }">
            <label>Name*</label>
            <input type="text" name="name" class="form-control" ng-model="name" 
                   ng-minlength="3" ng-maxlength="8" required>
            <p ng-show="loginForm.name.$dirty && loginForm.name.$error.required" 
               class="help-block">Name is required</p>
            <p ng-show="loginForm.name.$error.minlength" class="help-block">
               Name is too short.
            </p>
            <p ng-show="loginForm.name.$error.maxlength" class="help-block">
              Name is too long.
            </p>
        </div>         
        <!-- EMAIL -->
        <div class="form-group" ng-class="{ 'has-error' : 
             loginForm.userName.$invalid && !loginForm.userName.$pristine }">
            <label>UserName(email)*</label>
            <input type="email" name="userName" class="form-control" 
                   ng-model="userName">
            <p 
          ng-show="loginForm.userName.$invalid && !loginForm.userName.$pristine" 
            class="help-block">
              Enter a valid email.
            </p>
        </div>
        <div class="form-group" ng-class="{ 'has-error' : 
             loginForm.password.$invalid && !loginForm.password.$pristine }">
            <label>Password*</label>
            <input type="password" name="password" class="form-control" 
                   ng-model="password" ng-minlength="6" ng-maxlength="8" required>
            <p ng-show="loginForm.password.$invalid && !loginForm.password.$pristine" 
               class="help-block">Password must be between 6-8 characters.</p>
        </div>        
        <button type="submit" class="btn btn-primary" 
              ng-disabled="loginForm.$invalid">
          Submit
        </button>        
    </form>
    </div>
</body>
</html>

 

As you can see in above image, few key points are explained below.

  1. novalidate: it prevents the default HTML5 validation since we are validating each field manually.
  2. required: As explained above the field value is a must.
  3. ng-minlength and ng-maxlength: These attributes are used to set the minimum and maximum length for the field value.
  4. email type: The type “email” is used for validating a valid email field.
  5. password type: the type “password” is used for password fields where the value is kept as confidential without displaying to the user.

 

Now, let’s created an angular app and controller that we have already applied in index page which holds the code behind logic. The App.js page is shown below.

// create angular app
var validationApp = angular.module('validationApp', []);

// create angular controller
validationApp.controller('mainController', function($scope) {

 // function to submit the form after all validation has occurred   
 $scope.submitForm = function(isValid) {

  // check to make sure the form is completely valid
  if (isValid) { 
   alert('Login Form is valid');
  }
 };
});

 

In the above file, we can see that we are showing an alert message on form submission. This message is shown only if the form is valid. You can check whether form is valid or not as by passing the <formName>.$valid property to an submit function as shown on the index page.

 

Disabling HTML5 Validation:

The novalidate attribute prevents default HTML5 validation. If we don’t apply this attribute, our app looks ugly as shown below.

Instead of our manual message, this default message is shown.

Disabling the button using ng-disabled:

We want to disable our submit button if the form is not valid. It should be enabled only when all fields are filled correctly and valid. It means Name filed must be of a correct length, UserName should be valid email and password should be of a correct length, then the only button must be enabled.

This can be done using the ng-disabled attribute as shown below.

 <button type="submit" class="btn btn-primary" 
    ng-disabled="loginForm.$invalid">
   Submit
 </button>

 

Display an error message using ng-show:

When input field value is not valid, we would want to show an error message to the user. The ng-show attribute would fulfill our requirement.

Let’s add error message to our fields when they are not valid($invalid) and they have been used/modified($pristine)

<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : 
  loginForm.name.$invalid && !loginForm.name.$pristine }">
 <label>Name*</label>
 <input type="text" name="name" class="form-control" ng-model="name" 
     ng-minlength="3" ng-maxlength="8" required>
 <p ng-show="loginForm.name.$dirty && loginForm.name.$error.required" 
    class="help-block">Name is required</p>
 <p ng-show="loginForm.name.$error.minlength" class="help-block">
    Name is too short.
 </p>
 <p ng-show="loginForm.name.$error.maxlength" class="help-block">
   Name is too long.
 </p>
</div>

 

Applying conditional classes using ng-class:

Since we are using bootstrap, we can use the available classes i.e. has-error which provides a nice error and color to the form group. It provides a good look and feel to the UI.

ng-class is used to add classes based on some expression. In this case, we would want to apply a has-error class on form group when the input is invalid and pristine.

The syntax is :

ng-class="{ <class-you-want> : <expression to be evaluated > }"

1. Initially when the app is loaded.

2. When Name filed is not entered, it displays following error.

3. When Name field value less than the minimum length, it displays following error.

4. When the Name field value exceeds the maximum length, the error is displayed as shown in the below image.

5. When UserName is not a valid email, it shows error.
6. When User Name is not a valid email, unless you enter ‘@’ and next character, it shows following error.

7. Password field should match the specified length. If it does not meet, it shows the following error.

8. When the user enters all fields with correct value with all validations passed and the user clicks on Submit button, it displays an alert message of success. This is shown as below.

Conclusion:

This way of validation is easy and one can use this and make a better application with better look and feel of UI.

Preeti Dhavali

Leave a Comment

View Comments

  • ng-class="{ : }"
    Please provide the example to this because I am getting too confused with this line.

    • The ng-class directive helps to bind one or more CSS classes to an HTML element. The syntax ng-class="{ : }" indicates as we can provide more than one CSS based on condition.
      Ex :

      .rowColor1{
      border: 1px solid #F9F9F9;
      background-color: blue;
      }
      .rowColor2{
      border: 1px solid #FDFDFD;
      background-color: orange;
      }
      .rowColor3{
      border: 1px solid #F2F2F2;
      background-color: green;
      }

Share
Published by
Preeti Dhavali

Recent Posts

Everything You Need To Know About Create React App

The configuration of resources can be a time-consuming and difficult operation while creating a React…

3 weeks ago

Causes of CyberCrime and Preventive Measures

          Rapid technological growth and developments have provided vast areas of…

1 month ago

How Data Lineage will Improve Business Practices

How often have you thought about changing the way that you store and use data?…

1 month ago

10 Dominating Programming Language for Mobile App In 2022

Programming Languages are a set of rules that aid in transforming a concept into a…

1 month ago

What is Serverless Edge Computing? Features | Benefits

Serverless edge computing is a new technology with a lot of promise, but it can…

1 month ago

Are Your Accounts Protected Against Cyberattacks?

Do any of your passwords include personal names, date of birth, or pet names? If…

2 months ago