Introduction: In Today's Post I will explain how to do Validation with Jquery for Emailid, Phone number, numbers, Decimal and Required in single generic code. 

Post: Client side validation is the most common process in any web site. Even though we have jQuery form validation plug in also. But the issue we faced with this plug in is that We have to write separate code to validate every form. So I decided to write something generic that I can write once and not need to think about client side validation part in complete site. Luckily jQuery provide us option to do this easily.

One single code will validate the complete site. In the current post, I will do validation only for required, email id, phone number, and decimal values. With a little code of jQuery and some CSS, we can do it.

I am using 1.9.1 version of jQuery for this. Complete jQuery will work based on attribute values on controls. We can also use the class of controls. But I could not use that because I was adding some classes dynamically to controls. Here I am explaining the code in steps but you can find complete code in the last of the post.

Step 1. We write code to make sure no submit request goes without validation.

function BindValidationMethod(){
    jQuery(document).on("click","input:submit",function(e){
      if(jQuery(this).attr("disVal")){
        return true;
         }
     });
};

In above code, we create a method BindValidationMethod() that will hold the complete code for validation.

 jQuery(document).on("click","input:submit",function(e){ });

Above code will bind the function to execute on any submit button click. But sometimes we have to disable validation on some button so that they can do submit without validation. So we can place attribute “disval='1'” with that button. So

 
if(jQuery(this).attr("disVal")){
return true;
}

the code will return from the function without validation.

Step 2: Now we will create some CSS and methods to display the message on validation and remove after input value in control.

CSS:

<styletype="text/css">
.arrow-left
{
margin-top:12px;
float:left;
width:0;
height:0;
border-top:6pxsolidtransparent;
border-bottom:6pxsolidtransparent;
border-right:10pxsolid#e2e2e2;
z-index:1000;
}
.tool_tip
{
background:#e2e2e2;
color:red;
padding-left:5px;
padding-right:5px;
height:24px;
line-height:24px;
font-size:11px;
font-style:italic;
margin-top:8px;
float:left;
border:solid1pxsilver;
border-top-right-radius:7px;
border-bottom-right-radius:7px;
border-top-right-radius:4px;
border-bottom-right-radius:4px;
z-index:99;
}
.tooltip_outer
{
margin-top:-35px;
display:inline;
padding-left:170px;
margin-right:0px;
position:absolute;
z-index:2;
}
style>
function GetMessage(m){
  return "<divclass='tooltip_outer'><divclass='arrow-left'><divclass='tool_tip'>"+m+"";
}
function numericsonly(ob){
   var invalidChars=/[^0-9]/gi
   if(invalidChars.test(ob.value)){
     ob.value=ob.value.replace(invalidChars,"");
   }
}
function decimalonly(ob){
   var invalidChars=/[^0-9][^.][^0-9]/gi
   if(invalidChars.test(ob.value)){
     ob.value=ob.value.replace(invalidChars,"");
   }
}
function BindRemoveError(o,m){
   o.addClass("error");
   o.focus();
   o.after(GetMessage(m)).show("slow");
   o.on("blur",function(){
     o.next('.tooltip_outer').hide();
     o.removeClass("error");
  });
}

The getmessage method will be used to Get HTML to show validation message as per message passed as a parameter.

a numericsonly method will allow only numeric value in any text box.

a decimal only method will allow only decimal value in any text box.

BindRemoveError methods inject validation message next to control, Set focus on control and add a method to remove this validation message onblur event of control. Where “o” is control object and m is validation message. 

All above methods will be used while validation process.

$('input[num="1"]').on("keyup",function(){
   $(this).next('.tooltip_outer').hide();
   numericsonly(this);//definitionofthisfunctionisabove
});
$('input[dec="1"]').on("keyup",function(){
   $(this).next('.tooltip_outer').hide();
   decimalonly(this);//definitionofthisfunctionisabove
});

Bind above two on Document ready method. These will allow the user to input only number and decimal in the text box which is having attribute “num='1'” for only number and “dec='1'” for decimal only.

Step 3: Dropdown validation for required.

jQuery("select").each(function(){
   var o=jQuery(this);
   if(IsValid){
      if(o.attr("req")&&jQuery('option:selected',jQuery(this)).index()==0){
          e.preventDefault();
          BindRemoveError(o,"Required");
          IsValid=false;
     }
  }
});

this code will loop through all select (dropdown) which is having req=”1” attribute. If control is having req attribute and also SelectedIndex is 0 then validation error will be bind.

 

Step 4: Textbox validation for email id validation, phone number validation, and required field.

jQuery("input:text").each(function(){
    var o=jQuery(this);
     if(IsValid){
       if(o.attr("req")&&jQuery.trim(o.val())==''){
         e.preventDefault();
         BindRemoveError(o,"Required");
         IsValid=false;
       }

   }
  if(IsValid){
     if(o.attr("mob")&&(o.val().length!=10)){
        e.preventDefault();
        BindRemoveError(o,"Should be of 10 digits");
        IsValid=false;
     }
  }
  if(IsValid){
    var filter=/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if(o.attr("email")&&!(filter.test(o.val()))){
        e.preventDefault();
        BindRemoveError(o,"Not a valid mail Id");
        IsValid=false;
    }
 }
});

this code will loop through all textboxes on the page and check for req=”1”, mob=”1” and emal=”1”. If control is having these attributes than relative validation error will be bind.

Place this code on master page or layout page of site and you just need to place appropriate attribute to controls where you want to validate control.

<cc: cTextBoxID="txtregMobileNo" runat="server" req="1" num="1" mob="1">cc:cTextBox>

This is a custom control for text box but you can place these attribute with HTML text box or asp.net simple text box.

Complete Code Sample:

<styletype="text/css">
.arrow-left
{
margin-top:12px;
float:left;
width:0;
height:0;
border-top:6pxsolidtransparent;
border-bottom:6pxsolidtransparent;
border-right:10pxsolid#e2e2e2;
z-index:1000;
}
.tool_tip
{
background:#e2e2e2;
color:red;
padding-left:5px;
padding-right:5px;
height:24px;
line-height:24px;
font-size:11px;
font-style:italic;
margin-top:8px;
float:left;
border:solid1pxsilver;
border-top-right-radius:7px;
border-bottom-right-radius:7px;
border-top-right-radius:4px;
border-bottom-right-radius:4px;
z-index:99;
}
.tooltip_outer
{
margin-top:-35px;
display:inline;
padding-left:170px;
margin-right:0px;
position:absolute;
z-index:2;
}
style>
<scripttype="text/javascript">
   varmessageScript="";
   $('.required').next('.tooltip_outer_feedback').hide();
   $('.required_feedback').next('.tooltip_outer').hide();
   functionGetMessage(m){
     return"<divclass='tooltip_outer'><divclass='arrow-left'><divclass='tool_tip'>"+m+"";
   }
   functionnumericsonly(ob){
      varinvalidChars=/[^0-9]/gi
      if(invalidChars.test(ob.value)){
        ob.value=ob.value.replace(invalidChars,"");
      }
   }
   functiondecimalonly(ob){
      varinvalidChars=/[^0-9][^.][^0-9]/gi
      if(invalidChars.test(ob.value)){
        ob.value=ob.value.replace(invalidChars,"");
      }
   }
   jQuery(document).ready(function(){
      BindValidationMethod();
      $('input[num="1"]').on("keyup",function(){
         $(this).next('.tooltip_outer').hide();
         numericsonly(this);
      });
      $('input[dec="1"]').on("keyup",function(){
         $(this).next('.tooltip_outer').hide();
         decimalonly(this);
      });
  });
  functionBindRemoveError(o,m){
      o.addClass("error");
      o.focus();
      o.after(GetMessage(m)).show("slow");
      o.on("blur",function(){
        o.next('.tooltip_outer').hide();
        o.removeClass("error");
     });
  }
  functionBindValidationMethod(){
     jQuery(document).on("click","input:submit",function(e){
       if(jQuery(this).attr("disVal")){
         return true;
       }
       jQuery("select").each(function(){
         var o=jQuery(this);
         if(IsValid){
            if(o.attr("req")&&jQuery('option:selected',jQuery(this)).index()==0){
              e.preventDefault();
              BindRemoveError(o,"Required");
              IsValid=false;
            }
         }
      });
      jQuery("input:text").each(function(){
         var o=jQuery(this);
           if(IsValid){
            if(o.attr("req")&&jQuery.trim(o.val())==''){
               e.preventDefault();
               BindRemoveError(o,"Required");
               IsValid=false;
            }
         }
         if(IsValid){
           if(o.attr("mob")&&(o.val().length!=10)){
               e.preventDefault();
               BindRemoveError(o,"Shouldbeof10digits");
               IsValid=false;
           }
         }
        if(IsValid){
             varfilter=/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
             if(o.attr("email")&&!(filter.test(o.val()))){
                e.preventDefault();
                BindRemoveError(o,"NotavalidmailId");
                IsValid=false;
             }
        }
    });
    jQuery("input:password").each(function(){
       var o=jQuery(this);
       if(IsValid){
          if(o.attr("req")&&jQuery.trim(o.val())==''){
              e.preventDefault();
              BindRemoveError(o,"Required");
              IsValid=false;
           }

       }
       if(IsValid){
          if(o.attr("req")&&(o.val().length<6||o.val().length>8)){
              e.preventDefault();
              BindRemoveError(o,"Mustbebetween6to8");
              IsValid=false;
        }
      }
    });
  });
}
script>

Latest on posts

Blog Archive

Tags