Open In App

How to Validate Data in AngularJS ?

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know to validate the data in Angular JS, along with understanding the various ways to validate the data through the examples.

AngularJS allows client-side form validation. Form validation is necessary because it ensures that the data in the form is correct, complete, and are entered in the right manner, before submitting the form and sending details to the server. To validate the data, we need to validate both the form and the input fields and notify the user about the current state accordingly. If the user enters data in the wrong format, he should be notified about the same instead of submitting the wrong details.

For instance, if the user is asked to enter the phone number and the user enters “abcde”, the user should be asked to enter the phone number again and should be notified that only digits are allowed in this field. By performing form validation on the client-side, we ensure that correct and complete data is sent to the server.

There are several input controls that can be used in AngularJS form, which are given below:

  • input: It is used to get input data from the form in various types such as text, password, email, etc by changing its type.
<input type="text" name="name">
  • select: It is used to create a drop-down list.
<select> 
 <option>1</option> 
 <option>2</option>
</select>
  • button: It defines a clickable button to control other elements or execute a functionality.
<button name="submit">Submit</button>
  • textarea: It is used to get input long text content.
<textarea name="teaxtarea"></textarea>

AngularJS includes the following validation directives: 

  • ng-required: It can be used to put the required attribute on an input field, 
  • ng-minlength: It can be used to put the minimum length attribute on the input field, 
  • ng-maxlength: It can be used to put the maximum length attribute on the input field, 
  • ng-pattern: It can be used to put the pattern validation error key if the ngModel value doesn’t match the RegEx expression.

Example 1: This example describes the Form validation using validation directives

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
    </script>
</head>
 
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text"
               ng-model="name"
               name="name"
               ng-minlength=3
               ng-required="true"
               ng-pattern="/^[\w\s]*$/">
        <span ng-show="formname.name.$error.minlength"
              style="color:red">
            Minimum 3 characters required.
        </span>
        <span ng-show="formname.name.$error.pattern"
              style="color:red">Name can have only alphabets.
        </span>
        <br>
        <label>Phone:</label>
        <input type="tel"
               name="phone"
               ng-model="phone"
               ng-pattern="/^[0-9]*$/"
               ng-required="true"
               ng-minlength=6
               ng-maxlength=20>
        <span ng-show="formname.phone.$error.pattern"
              style="color:red">Phone number can have only digits.
        </span>
        <span ng-show="formname.phone.$error.minlength"
              style="color:red">Minimum 6 characters required.
        </span>
        <span ng-show="formname.phone.$error.maxlength"
              style="color:red">Minimum 10 characters required.
        </span>
        <br>
        <label>Email:</label>
        <input type="email"
               name="email"
               ng-model="email"
               ng-required="true"
               ng-pattern=
"/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/">
            <span ng-show="formname.email.$error.pattern"
                  style="color:red">Email has to be in format abc@gmail.com.
        </span>
        <br>
        <label>Message:</label>
        <br>
        <textarea name="message"
                  ng-model="message"
                  ng-required="true"
                  ng-maxlength=100></textarea>
            <span ng-show="formname.message.$error.maxlength"
                  style="color:red">Maximum length of message is 100 characters.
            </span>
    </form>
</body>
</html>


Output:

Example1

Explanation: In the above example, we have made a contact us form. The name of the form is ‘formname’. There are four fields in the form: name, phone, email, and message. We have used validation directives to validate the data entered by the user.

For the name, we have used the ng-required directive which means it is compulsory to enter the name, ng-pattern which has a regular expression for allowing only alphabets and space in the name, ng-minlength for ensuring that name has at least 3 characters, ng-maxlength for the maximum number of characters allowed in the name. We have used the directive ng-show directive for displaying the messages accordingly. The ng-show directive displays a message if the condition is true. For example, if the user enters a name that doesn’t match the regular expression specified in the ng-pattern directive formname.name.$error.pattern” will be true therefore “ng-show=formname.name.$error.pattern” will print the message “Name can have only alphabets”. Here we have used the $error object which contains the validation attributes that are applied to an element. Similarly, all the other fields: phone, email, the message have been validated.  

There are 2 ways for validating data in AngularJS. The first method is by using validation control states which include the form state and input state. The other method is using CSS classes.

Form State and Input State: The state of the form and the input fields are updated by AngularJS and these states are used to show useful messages to the user.

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
  • $dirty: The field has been modified
  • $valid: The field content is valid
  • $invalid: The field content is invalid

Forms have the following states:

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

These properties can be either true or false.

Example 2: This example describes the Form validation using form and field states.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
    </script>
</head>
 
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text"
               ng-model="name"
               name="name"
               ng-required="true"
               ng-pattern="/^[\w\s]*$/">
         <span ng-show=
"formname.name.$touched && formname.name.$error.required "
               style="color:red">
             Name is required and can have only alphabets.
         </span>
        <br>
        <label>Phone:</label>
        <input type="tel"
               name="phone"
               ng-model="phone"
               ng-pattern="/^[0-9]*$/"
               ng-required="true">
            <span ng-show=
"formname.phone.$invalid && formname.phone.$touched"
                  style="color:red">
                Phone number is required and can have only digits.
            </span>
        <br>
        <label>Email:</label>
        <input type="email"
               name="email"
               ng-model="email"
               ng-required="true"
               ng-pattern=
"/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/">
            <span ng-show=
"formname.email.$invalid && formname.email.$touched"
                  style="color:red">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <label>Message:</label>
        <textarea name="message"
                  ng-model="message"
                  ng-required="true"
                  ng-maxlength=100>
        </textarea>
            <span ng-show=
"formname.message.$invalid && formname.message.$touched"
                  style="color:red">
Message is required, maximum length of message can be 100 characters.
            </span>
        <br>
        <input type="submit"
               name="submit"
               ng-disabled="formname.$invalid">
    </form>
</body>
</html>


Output:

 

Explanation: In the above example we have used field states for validation. For the name we used ng-show = “formname.name.$touched && formname.name.$error.required ” which means if the field has been touched but the field is still empty the message “Name is required and can have only alphabets” is printed.

For phone number, we have used ng-show = “formname.phone.$invalid && formname.phone.$touched” which means if the field is touched and whatever the user entered is not valid then the required message is printed. Similarly, we have validated the email and message fields.

We have disabled the button if the condition “formname.$invalid” is true which means if any field in the form has invalid data the button will not be enabled. If data entered in all the fields are valid then the button will be enabled.

CSS classes for form validation: To allow styling of form as well as controls, ng-model adds CSS classes.

The following classes are added to or removed from the input field:

  • ng-untouched: Field has not been touched yet
  • ng-touched: Field has been touched
  • ng-pristine: Field has not been modified
  • ng-dirty: Field has been modified
  • ng-valid: Field content is valid
  • ng-invalid: Field content is invalid

The following classes are added to or removed from forms:

  • ng-pristine: No fields have not been modified yet
  • ng-dirty: One or more fields have been modified
  • ng-valid: The form content is valid
  • ng-invalid: The form content is not valid

Example 3: In this example, we are adding style to form and fields using CSS classes.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
    </script>
    <style>
        input.ng-invalid,
        textarea.ng-invalid {
            background-color: red;
        }
         
        input.ng-untouched,
        textarea.ng-untouched input.ng-pristine,
        textarea.ng-pristine {
            background-color: pink;
        }
         
        input.ng-touched,
        textarea.ng-touched {
            background-color: red;
        }
         
        input.ng-valid,
        textarea.ng-valid {
            background-color: green;
        }
         
        form {
            padding: 40px;
        }
         
        form.ng-invalid {
            background-color: #ed98a5;
        }
         
        form.ng-valid {
            background-color: #98edaf;
        }
    </style>
</head>
 
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text"
               ng-model="name"
               name="name"
               ng-minlength=3
               ng-required="true"
               ng-pattern="/^[\w\s]*$/">
            <span ng-show=
"formname.name.$error.minlength"
                  style="color:red">
               Minimum 3 characters required.
            </span>
            <span ng-show=
"formname.name.$error.pattern"
                  style="color:red">
               Name can have only alphabets.
            </span>
        <br>
        <label>Phone:</label>
        <input type="tel"
               name="phone"
               ng-model="phone"
               ng-pattern="/^[0-9]*$/"
               ng-required="true"
               ng-minlength=6
               ng-maxlength=20>
            <span ng-show=
"formname.phone.$error.pattern"
                  style="color:red">
                Phone number can have only digits.
            </span>
            <span ng-show=
"formname.phone.$error.minlength"
                  style="color:red">
                Minimum 6 characters required.
           </span>
           <span ng-show=
"formname.phone.$error.maxlength"
                 style="color:red">
                Minimum 10 characters required.
           </span>
        <br>
        <label>Email:</label>
        <input type="email"
               name="email"
               ng-model="email"
               ng-required="true"
               ng-pattern=
"/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/">
            <span ng-show=
"formname.email.$error.pattern"
                  style="color:red">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <label>Message:</label>
        <br>
        <textarea name="message"
                  ng-model="message"
                  ng-required="true"
                  ng-maxlength=100>
        </textarea>
            <span ng-show=
"formname.message.$error.maxlength"
                  style="color:red">
                Maximum length of message is 100 characters.
            </span>
    </form>
</body>
</html>


Output:

 

Explanation: In the above example we have used CSS classes to add style to the input controls and the form. Initially, the color of the form is red. For the input fields, if the user enters data that is invalid the color of the input control will change to red. If the user has not touched or modified the field its color will remain pink. If the user has touched the field but did not enter anything its color changes to red. If the user enters data that is valid its color changes to green. When all the fields have data that is valid the color of the form changes to green.

Example 4: In this example, we are creating the Registration Form by specifying the different validation checks.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
    </script>
  <style>
        input.ng-dirty {
            background-color: lightblue;
        }
         
        input.ng-valid {
            background-color: lightgreen;
        }
         
        span,
        p {
            color: red;
        }
         
        table {
            border-collapse: collapse;
            margin-bottom: 20px;
            margin-top: 10px;
        }
         
        tr,
        td,
        th {
            border: 1px solid black;
        }
    </style>
</head>
 
<body ng-app="myApp"
      ng-controller="myctrl">
    <h1>Registration Form</h1>
    <form name="formname">
        <label>First Name:</label>
        <input type="text"
               ng-model="firstname"
               name="firstname"
               ng-minlength=3
               ng-required="true"
               ng-pattern="/^[\w\s]*$/">
            <span ng-show=
"formname.firstname.$touched && formname.firstname.$error.required">
                Name is required.
            </span>
            <span ng-show=
"formname.firstname.$error.minlength">
                Minimum 3 characters required.
            </span>
            <span ng-show=
"formname.firstname.$error.pattern">
                Name can have only alphabets.
            </span>
        <br>
        <label>Last Name</label>
        <input type="text"
               ng-model="lastname"
               name="lastname"
               ng-minlength=3
               ng-required="true"
               ng-pattern="/^[\w\s]*$/">
            <span ng-show=
"formname.lastname.$touched && formname.lastname.$error.required">
                Name is required.
            </span>
            <span ng-show=
"formname.lastname.$error.minlength">
                Minimum 3 characters required.
            </span>
            <span ng-show=
"formname.lastname.$error.pattern">
                Name can have only alphabets.
            </span>
        <br>
        <label>Gender:</label>
        <br>
        <input type="radio"
               name="gender"
               ng-model="gender"
               value="Male"
               ng-required="true">
        <label>Male</label>
        <input type="radio"
               name="gender"
               ng-model="gender"
               value="Female"
               ng-required="true">
        <label>Female</label>
        <br>
        <label>Password</label>
        <input type="password"
               name="password"
               ng-model="password"
               ng-required="true"
               ng-minlength=6
               ng-maxlength=10>
            <span ng-show=
"formname.password.$touched && formname.password.$error.required">
                Password is required.
            </span>
            <span ng-show=
"formname.password.$error.minlength">
                Minimum 6 characters required.
            </span>
            <span ng-show=
"formname.password.$error.maxlength">
                Minimum 10 characters required.
            </span>
        <br>
        <label>Phone</label>
        <input type="tel"
               name="phone"
               ng-model="phone"
               ng-pattern="/^[0-9]*$/"
               ng-required="true"
               ng-minlength=6
               ng-maxlength=10>
            <span ng-show=
"formname.phone.$touched && formname.phone.$error.required">
                Phone is required.
            </span>
            <span ng-show="formname.phone.$error.minlength">
                Minimum 6 characters required.
            </span>
            <span ng-show=
"formname.phone.$error.pattern">
                Phone number can have only digits.
            </span>
            <span ng-show=
"formname.phone.$error.maxlength">
                Minimum 10 characters required.
            </span>
        <br>
        <label>Email:</label>
        <input type="email"
               name="email"
               ng-model="email"
               ng-required="true"
               ng-pattern="/^[a-z0-9/_$#%]+@[a-z]+[.]+[a-z]+$/">
            <span ng-show=
"formname.email.$touched && formname.email.$error.required">
                Email is required.
            </span>
            <span ng-show=
"formname.email.$error.pattern">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <select ng-model="city"
                name="city"
                ng-required="true">
            <option disabled="">Select city</option>
            <option ng-repeat="x in citylist">{{x}}</option>
        </select>
        <span ng-show=
"formname.city.$error.required">
            Select a city
        </span>
        <br>
        <label>Select technologies</label>
        <br>
        <input type="checkbox"
               name="option1"
               ng-model="checkboxvalue1"
               value="HTML">
        <label>HTML</label>
        <br>
        <input type="checkbox"
               name="option2"
               ng-model="checkboxvalue2"
               value="CSS">
        <label>CSS</label>
        <br>
        <input type="checkbox"
               name="option3"
               ng-model="checkboxvalue3"
               value="JavaScript">
        <label>JavaScript</label>
        <br>
        <input type="checkbox"
               name="option4"
               ng-model="checkboxvalue4"
               value="PHP">
        <label>PHP</label>
        <br>
        <p ng-if=
'!checkboxvalue1 && !checkboxvalue2 && !checkboxvalue3 && !checkboxvalue4'>
                Select a technology
        </p>
 
        <input type="submit"
               name="submit"
               ng-click="calculate()"
               ng-disabled="formname.$invalid">
    </form>
    <br>
    <table>
        <tr ng-repeat="x in list"
            ng-show="value!=0">
            <td>{{x.key}}</td>
            <td>{{x.value}}</td>
        </tr>
    </table>
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('myctrl', function($scope) {
            $scope.value = 0;
            $scope.firstname = '';
            $scope.city = "Select city";
            $scope.citylist = ["Mumbai", "Jaipur", "Pune"];
            $scope.calculate = function() {
                $scope.value += 1;
                $scope.list1 = [];
                if($scope.checkboxvalue1)
                    $scope.list1.push(formname.option1.value);
                if($scope.checkboxvalue2)
                    $scope.list1.push(formname.option2.value);
                if($scope.checkboxvalue3)
                    $scope.list1.push(formname.option3.value);
                if($scope.checkboxvalue4)
                    $scope.list1.push(formname.option4.value);
                $scope.list2 = $scope.list1.toString();
                $scope.list = [{
                    "key": "First name",
                    "value": $scope.firstname
                }, {
                    "key": "last name",
                    "value": $scope.lastname
                }, {
                    "key": "Gender",
                    "value": $scope.gender
                }, {
                    "key": "Phone",
                    "value": $scope.phone
                }, {
                    "key": "Email",
                    "value": $scope.email
                }, {
                    "key": "City",
                    "value": $scope.city
                }, {
                    "key": "Selected Technologies",
                    "value": $scope.list2
                }];
            }
        });
    </script>
</body>
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads