How to do validation in AngularJs


Validation is the one of important part of any library. In each library or Framework there will be different approach to do validation. Similarly there is some different way to do validation in AngularJs.

In AngularJs Form attribute play the main role in validation.

Now in below example we will see the demo example of doing validation of UserName and EmailId.

<!DOCTYPE html>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.min.js"></script>
    var app = angular.module('myApp', []);
     app.controller('MyController', function($scope) {
     $scope.user = 'chandradev';
     $ = '';

        <legend><b>Validation Example</b></legend>

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

                <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>

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

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



Point to remember:

1. In the above example ng-show=”myForm.user.$dirty && myForm.user.$invalid” is used to display the invalid message if the user type invalid data or left blank.

2. If the user will leave blank field then ng-show directive will display the error message as given below.

       <span ng-show="myForm.user.$error.required">UserName is required.</span>

3. For validation of emailid the given below code will do.

       <span ng-show="$">Invalid Email ID.</span>


In this article we learnt that how to do basic validation in angularJs


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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