Tuesday 15 August 2017

Form Validation In AngularJS Using ng-messages

In This Article I Would Like To Explain You About Form Validation In AngularJS Application using ng-messages.
For Form Validation Using ng-messages In AngularJS, We Have To Add Script File Link
i.e., <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></scriptAnd Also Should Add 'ngMessages' directive To The Angular Module .i.e.,

angular.module('angularformvalidationusingngmessage', ['ngMessages']);

For The Form Validation, We Have To Give Name For The Form tag i.e., <form name="formvalidation" novalidateAs The Input Controls Recognise By Using Name Of The Form Only.
And ‘novalidate’ Is For Not Validating The Form By Its Default, As We Are Giving The Validations And Validation Messages. AngularJS Monitors The State Of The Input Fields By
  Form Properties/Attributes

We Have To Use ng-messages Directive In div tag or any other tags, which is having sub tags, mentioned with single or more than one ng-message directives with error message to display i.e.,
<div  ng-messages="formvalidation.name.$error" >
    <p ng-message="maxlength">Name Should Contain Maximum 10 Characters</p>
    <p ng-message="maxlength">Name Should Contain Minimum 3 Characters</p>
    <p ng-message="pattern">Name Should Contain Only Letters</p>
    <p ng-message="required">Name Is Required</p>
 </div>

The Code As Below:

index.html


<!DOCTYPE html>
<html ng-app="angularformvalidationusingngmessage">
<head>
    <meta charset="utf-8" />
    <title>AngularJS - Form Validation</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
    <script src="index.js"></script>
    <style>
        input.ng-invalid {
            background-color: lightpink;
        }

        input.ng-valid {
            background-color: lightgreen;
        }
    </style>
</head>
<body ng-controller="FormValidationNgMessageController">
    <form name="formvalidation" novalidate>
        <div class="container">
            <div class="col-sm-8 col-sm-offset-2">

                <!-- Page Header -->
                <div class="page-header"><h1>AngularJS - Form Validation Using ng-messages</h1></div>
                <!-- Name -->
                <!-- Here In The Error Messages, I Give ng-show with condition For Both Max. and Min. Error Messages Because That It Had To Show Only One Message Instead Of Showing Two Messages Min/Max or Pattern Message, when If Both Messages are showing I restricted It To Display only Pattern Error Message -->
                <!-- If submitted is true then it looks for validation -->
                <div class="form-group" ng-class="{ 'has-error' : formvalidation.name.$invalid }">
                    <label>Name</label>
                    <input type="text" name="name" class="form-control" ng-model="Info.Name" ng-pattern="/^[a-zA-Z]*$/" ng-minlength="4" ng-maxlength="10" required>
                    <div style="color:red;" ng-messages="formvalidation.name.$error" ng-if="formvalidation.name.$touched || submitted">
                        <p ng-message="maxlength">Name Should Contain Maximum 10 Characters</p>
                        <p ng-message="maxlength">Name Should Contain Minimum 3 Characters</p>
                        <p ng-message="pattern">Name Should Contain Only Letters</p>
                        <p ng-message="required">Name Is Required</p>
                    </div>
                    </div>

                <!-- Mobile Number -->
                <!-- Maximum Length Is Restricted To 10 By Giving Attribute 'maxlength="10" And Also If Mobile Number Is Not Starts With 7,8,9 It Shows Error Message-->
                <!-- Mobile Number Pattern Is Given as ng-pattern="/(7|8|9)\d{9}/" -->
                <div class="form-group" ng-class="{ 'has-error' : formvalidation.phonenumber.$invalid }">
                    <label>Mobile Number</label>
                    <input type="text" name="phonenumber" class="form-control" ng-model="Info.PhoneNumber" maxlength="10" ng-pattern="/(7|8|9)\d{9}/" required>
                    <div style="color:red;" ng-messages="formvalidation.phonenumber.$error" ng-if="formvalidation.phonenumber.$touched || submitted">
                        <p ng-message="pattern">Invalid Mobile Number, Should Start With 7 or 8 or 9</p>
                        <p ng-message="required">Phone Number Is Required</p>
                    </div>
                    </div>
                <!-- PAN Number -->
                <!-- PAN Number Pattern Is Given as ng-pattern="/^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/" And It Converts The Any Case To Uppercase Only Using style="text-transform: uppercase" -->
                <div class="form-group" ng-class="{ 'has-error' : formvalidation.pannumber.$invalid  }">
                    <label>PAN Number</label>
                    <input type="text" name="pannumber" class="form-control" ng-model="Info.PANNumber" maxlength="10" style="text-transform: uppercase" ng-pattern="/^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/" required>
                    <div style="color:red;" ng-messages="formvalidation.pannumber.$error" ng-if="formvalidation.pannumber.$touched || submitted">
                        <p ng-message="pattern" ">Invalid PAN Number</p>
                        <p ng-message="required">PAN Number Is Required</p>
                    </div>

                <!-- Email -->
                <!-- Emailr Pattern Is Given as ng-pattern="/^.+@.+\..+$/" And It Converts The Any Case To Lowercase Only Using style="text-transform: lowercase" -->
                <div class="form-group" ng-class="{'has-error':  formvalidation.email.$invalid}">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" ng-model="Info.Email" style="text-transform: lowercase" ng-pattern="/^.+@.+\..+$/" required>
                    <div style="color:red;" ng-messages="formvalidation.email.$error" ng-if="formvalidation.email.$touched || submitted">
                        <p ng-message="required">Email Is Required</p>
                        <p ng-message="pattern">Invalid Email</p>
                        </div>
                    </div>
                <!-- Submit Button -->
                <div class="form-group">
                    <button type="submit" class="btn btn-primary" ng-click="SubmitForm()">Submit</button>
                </div>
            </div>
        </div>
    </form>

</body>
</html>

index.js

var app = angular.module('angularformvalidationusingngmessage', ['ngMessages']);
app.controller('FormValidationNgMessageController', function ($scope, $window) {

    $scope.SubmitForm = function () {
       
        if ($scope.formvalidation.$valid) {
            $scope.submitted = false;
            alert("Submitted!!");
        }
        else {
            //if $scope.formvalidation.$valid is not true then it submitted= true i.e., the submitted attribute should work
            $scope.submitted = true;
        }

    }

});


Output:-

After Loading The Page It Shows As Below:
 Without Filling The Input Controls If We Click On Submit Button, It Shows As Below:

 If We Give The Invalid Information Then, It Shows Error Messages As Below:
  If We Give Number In Name Input Box , It Shows The Following Error Message As Below :
 After Giving The Correct Information Which It Meets The Criteria, It Shows As Below:

No comments:

Post a Comment

Note: only a member of this blog may post a comment.