My Blog List

Thursday, 30 June 2016

Perfect Validation

              This gonna be a bit longer post than the previous one. I hope everyone should read it till the last. At the end, you will learn about the perfect validation in the lesser code. I am damn sure about that I will explain my best to you.

I will divide the validation into three types :

#Type1:


Validation without Javascript : 

            It is already predefined validation in HTML5. we can easily validate using the HTML tags. I used this trick to win the prizes in intercollegiate meets and symposiums in my academic time.

Example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form>
    <fieldset>
        <legend>Booking Details</legend>
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" value="" aria-describedby="name-format" required="" pattern=[a-zA-Z]+ >
          
        </div>
        <div>
            <label for="email">Email (required):</label>
            <input type="email" id="email" name="email" value="">
        </div>
        <div>
            <label>Website:</label>
            <input type="url" id="website" name="website" value="">
        </div>
        <div>
            <label for="numTickets"><abbr title="Number">No.</abbr> of Tickets (required):</label>
            <input type="number" id="numTickets" name="numTickets" value=""   min="10" max="15">
        </div>
        <div class="submit">
            <input type="submit">
        </div>
    </fieldset>
</form>    
</body>
</html>

       But I wouldn't recommend you to follow this type of validation. Because the internet users live in different locations even somebody lives in the remote villages. So,in that case the HTML5 doesn't work in the obsolete browsers (Not an Updated Browsers ).

Download Source : Click Here 

#Type2: 

Validation with AngularJS :-

              By using AngularJS, We can validate the form in very less code. For example, even in the 3kb of memory space, we can do validation easily.

Example:
     
 <form name="frm">

<span>Enter your Name:</span>

<input type="text" name="name" ng-model="user.name" pattern="[a-zA-Z]+" required ng-minlength="5" ng-maxlength="7"><br>

<span ng-show="frm.name.$dirty && frm.name.$valid">
 Correct value
</span><br>

<span ng-show="frm.name.$dirty && frm.name.$error.pattern">
this is not a name this is number
</span>

<span ng-show="frm.name.$dirty && frm.name.$error.minlength">
 very short character
</span>

<span ng-show="frm.name.$dirty && frm.name.$error.maxlength">
very long character
</span>

<span>Enter your Number:</span>

<input type="number" name="number" ng-model="user.number"     min="5" max="7" required ><br>

<span>Enter your Email:</span>

<input type="email" name="email" ng-model="user.email" required><br>

<span ng-show="frm.email.$dirty && frm.email.$error.requried">
     Required
</span>

<span ng-show="frm.email.$dirty && frm.email.$error.email">
not a email
</span>

<span>Enter your URL:</span>

<input type="url" name="url" ng-model="user.url" required><br>

<span>Enter your Time:</span>

<input type="time" name="time" ng-model="user.time" required><br>

<span>Enter your Date:</span>

<input type="date" name="date" ng-model="user.date" required><br>

<span>Enter your Week:</span>

<input type="week" name="week" ng-model="user.week" required><br>

<button ng-disabled="frm.$invalid">Insert data </button>

</form>

       
Download Source : Click Here 
      
#Type3: 

Validation with AngularJS Additional Module 
(ng-message) :-

                 By comparing those previous two types of the validation, I recommend everyone to do the validation by using this module. I will tell why I prefer this type of validation in the following scenario.
             The name field in the form must be filled only by the string. But if the user tries to type one number in that field, we have to show them the two error messages. (1.pattern & 2.min-length) . Now We got two error messages.(1.pattern & 2.min-length)
But this is not a good way, we can't give the priority to the validation. So we have to use this ng-message module. Here we will see how to set priority in the following code. 

Example:


<form name="frm">
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>

    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" ng-model="Email" name="Email" ng-minlength="5" ng-maxlength="25" required>

  </div>

 <div ng-messages="frm.Email.$error" role="alert" class="my-messages" ng-if="frm.Email.$dirty">

    <div ng-message="required" class="some-message">Please enter a value for this field.</div>

    <div ng-message="email">This field must be a valid email address.</div>

    <div ng-message="maxlength">This field can be at most 15 characters long.</div>

     <div ng-message="minlength">This field can be at min 5 characters be filed.</div>

  </div>


<div class="form-group">

    <label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ng-model="password" name="password" ng-minlength="5" 
    ng-maxlength="15" required >

</div>

<div ng-messages="frm.password.$error" role="alert" ng-if="frm.password.$dirty">

<div ng-message="required">Please enter a value for this field.</div>

<div ng-message="maxlength">This field can be at most 15 characters long.</div>

<div ng-message="minlength">This field can be at min 5 characters be filed.</div>

</div>

<div class="form-group">

    <label for="exampleInputPassword1">Conform Password:</label>
    <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Conform Password" ng-model="password2" name="password2" ng-pattern="password" required ng-minlength="5" 
    ng-maxlength="15">

</div>

<div ng-messages="frm.password2.$error" role="alert" ng-if="frm.password2.$dirty">

        <div ng-message="pattern">Password is Not match</div>

        <div ng-message="required">Please enter a conform password.</div>

        <div ng-message="maxlength">Password is Not match</div>

        <div ng-message="minlength">Password is Not match</div>
</div>


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

</form>


              We can set the priority in this type of validation. By comparing the previous type of AngularJS, it contains lesser code. By doing this type of validation, we can easily animate the validation message. 
             Here, I attached the ng-animate module in the following example, 


 Css Script : 


.ngMessages_animationClass {
    height: 50px;
    width: 350px;
}

.ngMessages_animationClass.ng-active-add {
    transition: 0.3s linear all;
    background-color: red;
}

.ngMessages_animationClass.ng-active {
    background-color: red;
}

.ngMessages_animationClass.ng-inactive-add {
    transition: 0.3s linear all;
    background-color: white;
}

.ngMessages_animationClass.ng-inactive {
    background-color: white;
}

.ngMessageClass {
    color: white;
}

.ngMessageClass.ng-enter {
    transition: 0.3s linear all;
    color: transparent;
}

.ngMessageClass.ng-enter-active {
    color: white;
}

.ngMessageClass.ng-leave {
    transition: 0.3s linear all;
    color: white;
}

.ngMessageClass.ng-leave-active {
    color: transparent;
}

JavaScript file :

var app = angular.module('myApp', ['ngAnimate', 'ngMessages']);

Html File : 



<input ng-model="ngModelSample" id="modelSample" name="modelSample" 

type="password"  ng-minlength="5" ng-maxlength="10" required 

class="ngMessageSample" />



<div ng-messages="messageAnimationForm.modelSample.$error" 

class="ngMessages_animationClass" ng-messages-multiple>


     <div ng-message="minlength" class="ngMessages_animationClass">

                  * It's mandatory at least 5 characters

     </div>



     <div ng-message="maxlength" class="ngMessages_animationClass">

                 * It's mandatory at most 10 characters

      </div>

</div>


Download Source : Click Here 


Some useful Idea on Validation :
        Now am gonna share something which will be useful On the validation. Mostly many people won't need to use this step. But am damn sure to say this it will be more effective if you use this on your coding.
         Now we will see about that directive and how it will function on the code. In case of filling the form like apply passport, We have to fill the various fields on that time, after typed all the necessary fields accidentally we pressed the reload (F5)key or navigation link to another page. so, for that action we need an alert box that contains 'leave this page' or 'stay in this page'. I will provide this code in the following example.

Example :
     
<html ng-app="myForm">
<head>
<script src="http://code.angularjs.org/1.5.6/angular.min.js">
</script>
<script type="text/javascript">
 var myForm =angular.module("myForm", []);
 myForm.directive('reconsider', function() {
 return {
        link: function($scope, elem, attrs) {
         window.onbeforeunload = function(){
           if ($scope.frm.$dirty) {
            return "you are not yet finished this";
            }
           }
$scope.$on('$locationChangeStart', function(event, next,current) {
         if ($scope.frm.$dirty) {
         if(!confirm("you are not yet finished this")) {
         event.preventDefault();
         }
                                }
                });
         }
        };
    });

  myForm.controller('rajkumar',['$scope',function($scope){

        var initial = {text: ''};
        $scope.OurModel = angular.copy(initial);   
  }]);
  </script>
<body>
<a href="http://google.com">google </a>

<div >

    <form name="frm" ng-controller="rajkumar" reconsider>
     <input name="input" ng-model="OurModel.text">
    </form>
    </div>
</body>
</html>


Download Source : Click Here 


ANGULAR UI – Ng-MASK( 3rd Party Library )

                In AngularJS, angular-ui/ ui-mask directive is useful to maintaining the pre-determined pattern sensitive type of data like Mobile No,RationCard, Passport No & Credit Card No)
Basically this type of data contains some pre-determined pattern (Example: Passport no- IND 98765432. In the case of passport no, the first three position must contains the string and the remaining contains the integer.

                     If we wrongly type any number or special characters in the first three positions, it will give the error message likewise in the remaining positions if we type the string, it will not validate to the further pages. 


                       In this type of  validation, we put the Mask directive on an input field so the user can only type pre-determined pattern, it will give more benefits than the other types. Here I attach a some example of sensitive Data (Ration Card Number)

Step:1 --- > Download Angular-mask Lib . 

Install Ng-Mask :  bower install angular-mask --save

Alternative :  Click here


Step:2 --- > Link to <head> tag section  
   (<script type="text/javascript" src="Lib/ngMask.min.js"></script>


Step:3 --- > Add to dependency on main module     
  (var myApp=angular.module("myApp",['ngMessages','ngMask']);



Step:4 --- > Add mask Directive on input filed
 Our Rationcard Pattern is (01/G/0782952)  
<input type="text" class="form-control" name="RationCard"
 mask='dd/A/ddddddd' required  >


Here, 

d-> Only Number
A->Only Caps 

   

Example File

index.html

<html>
<head>
<script type="text/javascript" src="Lib/angular.min.js"></script>
<script type="text/javascript" src="Lib/angular-messages.min.js"></script>

<script type="text/javascript" src="Lib/ngMask.min.js"></script>
</head>


<body>
<div class="form-group">
    <label for="exampleInputEmail1">Enter Your RationCard:(01/G/0782952)</label>
    <input type="text" class="form-control" id="exampleInputName" placeholder="01/G/0782952" ng-model="RationCard" name="RationCard" mask-clean="true" mask='dd/A/ddddddd' required  >
  </div>

<div ng-messages="frm.RationCard.$error" role="alert" ng-if="frm.RationCard.$dirty" style="color:maroon"> 
  <div ng-message="mask">RationCard is should be comes (01/G/0782952) this format</div>
         <div ng-message="required" class="ngMessagesClass">RationCard is must fill</div>
      


  </div>

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

</form>

App.js

var myApp=angular.module("myApp",['ngMessages','ngMask']);


Common Patterns

'*' => /./
Any single character

'w' => /\w/
Any word character (letter, number, underscore)

'W' => /\W/
Any nonword
character

'd' => /\d/
Any digit

'D' => /\D/
Any nondigit

's' => /\s/
Any whitespace character

'S' => /\S/
Any nonwhitespace
character

Download Source : Click Here 


Thank you..! Have a nice Day  :) 

Content Writer : Ganesh 

No comments:

Post a Comment