• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

AngularJS Form Validation with ngMessages

June 6, 2016 by javainterviewpoint Leave a Comment

Almost all the web application has forms for receiving the data from the user. It allows the users to type in and the data will be processed in the backend. In AngularJS the forms will be  synchronized to its model with the two-way data binding in angularjs through the ngModel directive. Lets see how AngularJS can benefit us when working with forms, especially during validation and various states of the forms.

AngularJS Form Validation Example

Lets take a simple login form example and see how we can add validation to it.

 <!DOCTYPE html>
<html>
<head>
  <meta charset="ISO-8859-1">
  <title>AngularJS Form Validation Example</title>
  <script
   src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
  </script>
</head>
<body ng-app="myApp">
  <div ng-controller="LoginCtrl">
  <script type="text/javascript">
    angular.module('myApp', []).controller('LoginCtrl',
    function($scope) 
    {
      $scope.login = function(username,password) 
      {
        if(username == 'Java' && password == 'InterviewPoint')
        {
          alert("Correct User"); 
        } 
        else
        {
          alert("Invalid User"); 
        }
    };
  });
 </script>
   <form name="loginform">
     <label>UserName :</label> 
     <input type="text" ng-model="username"
       placeholder="Enter your User Name" required ng-minlength="5" /></br>
     </br> <label>Password :</label> 
     <input type="text" ng-model="password"
       placeholder="Enter your Password" required /></br>
     </br>
     <button ng-click="login(username,password)"
       ng-disabled="loginform.$invalid">Login</button>
   </form>
 </div>
</body>
</html>

How things work here ?

  1. we have added a simple form, for which we have given the name as “loginform”
  2. Added HTML5 Validation tag “required” to each input fields to make it mandatory
  3. We have added a validator ng-minlength, which enforces that the minimum length of the value in the input field for the username is 5 characters
  4. To the submit button we have added the directive ng-disabled. This disables the submit button when the condition is satisfied. In our case we the “Login” button will be disabled when the form “loginform” is $invalid.

Output :

Hit on the URL : http://localhost:8080/AngularJS_Tutorial/LoginForm.html

You could see that the “Login” button will be disabled until the form validations are cleared. (i.e) a valid username is entered as it is a mandatory field and the length should be greater than 5 characters and password is entered as it is also a required field.

AngularJS Form Validation

Form State in AngularJS

AngularJS has the below 5 form states

Form State Description
$invalid AngularJS sets this state when any of the validations like
requried, ng-minlength, ng-maxlength etc on the any of the fields on the form is invalid
$valid This is inverse of $invalid state, this state is set when all the validation
in the form is evaluation to correct
$pristine All forms in angularjs starts with this state, this state tells us the fields which
is not modified by the user
$dirty $dirty is inverse of $pristine, it tells the user has modified
the form element
$error This state contains all errors on each form element

All the states mentioned above except $error are boolean and can be used as condition to show, hide, disable or enable any form element.

Displaying Error Message

Using the validators we can of-course enable or disable submit button but it doesn’t serve the purpose. We need to tell the user what went wrong and what has to be fixed.

<!DOCTYPE html>
<html>
<head>
  <meta charset="ISO-8859-1">
  <title>AngularJS Form Validation Example</title>
  <script
   src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
  </script>
</head>
<body ng-app="myApp">
  <div ng-controller="LoginCtrl">
  <script type="text/javascript">
    angular.module('myApp', []).controller('LoginCtrl',
    function($scope) 
    {
      $scope.login = function(username,password) 
      {
        if(username == 'Java' && password == 'InterviewPoint')
        {
          alert("Correct User"); 
        } 
        else
        {
          alert("Invalid User"); 
        }
    };
  });
 </script>
   <form name="loginform">
     <label>UserName :</label> 
     <input type="text" name="uname" ng-model="username"
       placeholder="Enter your User Name" required ng-minlength="5" /></br>
 
     <span style="color:red" ng-show="loginform.uname.$error.required">Username has to be 
entered</span>
     <span style="color:red"ng-show="loginform.uname.$error.minlength">Username has to be 
minimum 5 Character length</span>
 
     </br> <label>Password :</label> 
     <input type="text" name="pwd" ng-model="password"
      placeholder="Enter your Password" required /></br>
 
     <span style="color:red" ng-show="loginform.pwd.$error.required">Password has to entered</span>
     </br>
     <button ng-click="login(username,password)"
       ng-disabled="loginform.$invalid">Login</button>
   </form>
 </div>
</body>
</html>

What are the changes made ?

  1. First we have added the name attribute to the input fields, “uname” for username textbox and “pwd” for password textbox. When we add a name to any input, it creates a model on the form for that particular input, with the error state.
  2. So now we can access the errors which occured in the username field by using “loginform.uname.$error.required” when the username is not entered and “loginform.uname.$error.minlength” when the minimum length criteria is not satisfied. Similarly for Password field “loginform.pwd.$error.required” when the password is not entered.

AngularJS Form Validation with ngMessages

In the above code we have added the ng-show directive to each of the field to display the error message. Before the release of ngMessages developers has to rely on the ng-show directive to display the error message. ngMessages is bundled in AngularJS 1.3 release, ngMessages added enhanced support for displaying messages to the user especially error messages during form validation.

<!DOCTYPE html>
<html>
<head>
  <meta charset="ISO-8859-1">
  <title>AngularJS Form Validation Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.js"></script>
</head>
<body ng-app="myApp">
  <div ng-controller="LoginCtrl">
  <script type="text/javascript">
    angular.module('myApp', ['ngMessages']).controller('LoginCtrl',function($scope) 
    {
      $scope.login = function(username,password) 
      {
         if(username == 'Java' && password == 'InterviewPoint')
         {
            alert("Correct User"); 
         } 
         else
         {
            alert("Invalid User"); 
         }
     };
   });
 </script>
 <form name="loginform">
   <label>UserName :</label> 
   <input type="text" name="uname" ng-model="username"
      placeholder="Enter your User Name" required ng-minlength="5" /></br>

   <div ng-messages="loginform.uname.$error">
     <div style="color:red" ng-message="required">Username has to be entered..</div>
     <div style="color:red" ng-message="minlength">Username has to be minimum 5 Character length..</div>
   </div> 
 
   </br> <label>Password :</label> 
   <input type="text" name="pwd" ng-model="password"
      placeholder="Enter your Password" required /></br>
 
   <div ng-messages="loginform.pwd.$error">
     <div style="color:red" ng-message="required">Password has to be entered..</div>
   </div> 
   </br>
   <button ng-click="login(username,password)"
      ng-disabled="loginform.$invalid">Login</button>
   </form>
 </div>
</body>
</html>

What are the changes made ?

  1. ngMessages will be bundled in a seperate js “angular-messages.js” we have included that as a first step.
  2. In order to use ngMessages module we need to include it as our module dependency, which we have added in our angular.module
  3. Thats all ngMessages will handle showing and hiding specific messages based on the errors. Basically ngMessages loops through the form fields errors, loginform.uname.$error for our username and loginform.pwd.$error for our password field.
  4. input type “name” field can basically have only 3 validations required, minlength, maxlength and those were mentioned in the ng-message attribute with the corresponding validation message.

Output :

ngMessages Example

Other interesting articles which you may like …

  • AngularJS Hello World Example
  • AngularJS – Modules and Controllers
  • Two-Way Data Binding in AngularJS Example
  • ngBind, ngBindHtml and ngBindTemplate
  • AngularJS Routing Example using ngRoute
  • AngularJS Spring MVC integration
  • AngularJS Spring MVC CRUD Example using $http service

Filed Under: AngularJS, J2EE, Java Tagged With: AngularJS Form Validation, Form Validation, ngMessages

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·