Friday, February 4, 2011

TextBox Validations in ASP.Net using JavaScript

Hi Friendz,

       After so long dyas I am going to Post my next technical blog today. It depends on Textbox validations in ASP.Net using JavaScript.

     
Sometimes depend on conditions or requirement we need to validate controls on our webpage. This achieves in two ways, either using Server side validations or by using client side validations. We are going to use client side validations using JavaScript.


Conditions for Textboxes :

1.      Textbox1 to Textbox5 –

a)      Allow user to enter only numbers with or without decimal point.
b)      If user enter integer number (without decimal point), then after leaving control it should automatically complete with .00 (e.g. if user enter only 34 then when he leaves the control, the value of control should be 34.00).
c)       Don’t allow users to enter more than 2 digits after typing decimal point. Same as currency validation.
d)      Don’t allow user to give value 0 in Textbox.

2.      Textbox6 –

a)      Don’t allow user to type in this textbox (Read-Only).
b)      The textbox value should be the sum of values from Textbox1 to Textbox5.
c)       It should be auto calculated. Means if user types value in Textbox1 the value in this Textbox should be Textbox1 value. When user type some value in Textbox2 or any Textbox the value of this Textbox should be auto increment or vice-versa.
d)      Total should be round off to two digits after decimal point.

All these requirements are achieved through JavaScript in Asp.Net –

*Condition ‘1 a’ is achieved by using validatenumber function.

function validatenumber(event, obj) 
    {  
          var code = (event.which) ? event.which : event.keyCode;   
          var character = String.fromCharCode(code);
          if ((code >= 48 && code <= 57))   
          {
              // check digits      
              // Disallow all numbers if the entry is 0     
              if (obj.value =="0")       
              return false;      
             
              if (!isNaN(obj.value))     
              { 
                  if (obj.value =="0.0" && code == 48)       
                  {         
                     alert("Value cannot be less than 0.01");         
                     return false;       
                  }
               }      
               return true;   
           }
           else if (code == 46)   
           {
              // Check dot     
              if (obj.value.indexOf(".") < 0)     
              {       
                 if (obj.value.length == 0)        
                 obj.value ="0";        
                 return true;     
               }   
           }   
           else if (code == 8 || code == 116)   
           {
              // Allow backspace, F5     
              return true;   
           }   
           else if (code >=37 && code <= 40)   
           {
              // Allow directional arrows     
              return true;   
           }    
           return false; 
      }

 
*Condition ‘1 b and d’ is achieved by using validatefield function.

function validatefield(obj) 
      {
          clearInterval(interval);
          if(obj.value.length != 0)
          {
              if (obj.value.indexOf(".") == -1)   
              {     
                  obj.value = obj.value + ".00";
              }
             
              if(obj.value < 0.01)
              {
              obj.value = "";     
              alert("Value cannot be less than 0.01.");   
              }
          }
           
          // Clear text box if not a number, incase user drags/drop letter into box   
          else if (isNaN(obj.value))   
          {     
              obj.value = "";
          }   
       }
      
*Condition ‘1 c’ is achieved by using twodigits function.

  function twodigits(obj) 
      {
          var finddot = obj.value.split('.');
          var chkdamt = finddot.length - 1;
          if (chkdamt != '0') {
              if (finddot[1].length > 1) {
                  return false;
              }
          }
          return true;    
       }

*Condition ‘2’ is achieved by using startCalc and calc function.

function calc()
    {
        one = document.form1.TextBox1.value;
        two = document.form1.TextBox2.value;
        three = document.form1.TextBox3.value;
        four = document.form1.TextBox4.value;
        five = document.form1.TextBox5.value;
        document.form1.TextBox6.value = (one * 1) + (two * 1) + (three * 1) + (four * 1) + (five * 1);
    }

function startCalc()
    {
        interval = setInterval("calc()",1);  // Clear this interval in validatefield function
    }


Call these functions in appropriete events of textbox. Here I used onFocus, onKeypress, onBlur and onKeydown events.

1.          onFocus – startCalc()
2.          onKeypress – validatenumber(event, this)
3.          onBlur – validatefield(this)
4.          onKeydown - twodigits(this)

Total Code :

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
   
    function startCalc()
    {
        interval = setInterval("calc()",1);
    }
   
    function calc()
    {
        one = document.form1.TextBox1.value;
        two = document.form1.TextBox2.value;
        three = document.form1.TextBox3.value;
        four = document.form1.TextBox4.value;
        five = document.form1.TextBox5.value;
        document.form1.TextBox6.value = (one * 1) + (two * 1) + (three * 1) + (four * 1) + (five * 1);
    }
   
    function validatenumber(event, obj) 
    {  
          var code = (event.which) ? event.which : event.keyCode;   
          var character = String.fromCharCode(code);

                    
          if ((code >= 48 && code <= 57))   
          {
              // check digits      
              // Disallow all numbers if the entry is 0     
              if (obj.value =="0")        
              return false;      
             
              if (!isNaN(obj.value))     
              { 
                  if (obj.value =="0.0" && code == 48)       
                  {         
                     alert("Value cannot be less than 0.01");         
                     return false;       
                  }
               }      
               return true;   
           }
           else if (code == 46)   
           {
              // Check dot     
              if (obj.value.indexOf(".") < 0)     
              {       
                 if (obj.value.length == 0)        
                 obj.value ="0";        
                 return true;     
               }   
           }   
           else if (code == 8 || code == 116)   
           {
              // Allow backspace, F5     
              return true;   
           }   
           else if (code >=37 && code <= 40)   
           {
              // Allow directional arrows     
              return true;   
           }    
           return false; 
      }  
     
      function validatefield(obj) 
      {
          clearInterval(interval);
          if(obj.value.length != 0)
          {
              if (obj.value.indexOf(".") == -1)   
              {     
                  obj.value = obj.value + ".00";
              }
             
              if(obj.value < 0.01)
              {
              obj.value = "";     
              alert("Value cannot be less than 0.01.");   
              }
          }
           
          // Clear text box if not a number, incase user drags/drop letter into box   
          else if (isNaN(obj.value))   
          {     
              obj.value = "";
          }   
       }
       
       function twodigits(obj) 
      {
          var finddot = obj.value.split('.');
          var chkdamt = finddot.length - 1;
          if (chkdamt != '0') {
              if (finddot[1].length > 1) {
                  return false;
              }
          }
          return true;             
       }
        

     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 282px; height: 145px">
            <tr>
                <td style="width: 77px">
                    textbox1</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox1" runat="server" onFocus="startCalc();" 
                                               onkeypress="return validatenumber(event, this);"
                                               onblur="validatefield(this);"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 77px">
                    textbox2</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox2" runat="server" onFocus="startCalc();" 
                                               onkeypress="return validatenumber(event, this);"
                                               onblur="validatefield(this);"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 77px">
                    textbox3</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox3" runat="server" onFocus="startCalc();"
                                               onkeypress="return validatenumber(event, this);"
                                               onblur="validatefield(this);"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 77px">
                    textbox4</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox4" runat="server" onFocus="startCalc();"
                                               onkeypress="return validatenumber(event, this);"
                                               onblur="validatefield(this);"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 77px">
                    textbox5</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox5" runat="server" onFocus="startCalc();"
                                               onkeypress="return validatenumber(event, this);"
                                               onblur="validatefield(this);"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 77px">
                    Sum</td>
                <td style="width: 280px">
                    <asp:TextBox ID="TextBox6" runat="server" ReadOnly="true" Font-Bold="True" ForeColor="#C00000"></asp:TextBox></td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Attributes.Add("onkeydown", "return twodigits(this);");
        TextBox2.Attributes.Add("onkeydown", "return twodigits(this);");
        TextBox3.Attributes.Add("onkeydown", "return twodigits(this);");
        TextBox4.Attributes.Add("onkeydown", "return twodigits(this);");
        TextBox5.Attributes.Add("onkeydown", "return twodigits(this);");

    }
}

Hope guys this Post will be useful to you for your task  in future. If any changes or shortcuts is available don’t hesitate to comment.

Bye for now. I will back in next few days with next topic.
When Ordinary Programmer wakeup, the Elite Programmers begin to tremble in their Boots.
Take care.