ASP.NET Sever Controls Validation using JavaScript / jQuery!

I see many people posting questions in forums asking about client side validation of ASP.NET Server controls using JavaScript or jQuery!

First we will see how to allow only numeric digits in an ASP.NET Textbox using JavaScript! Check the below code snippet on how to do it!

Numeric Textbox
  1. <div>
  2.      <label style="float:left;">Enter you PIN:</label> <asp:TextBox runat="server" onkeydown="return NumericTextBox(event);"></asp:TextBox>
  3.    </div>
  4.    <script type="text/javascript">
  5.        
  6.        function NumericTextBox(evt) {
  7.            var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
  8.            if (charCode == 8 || //backspace
  9.                 charCode == 46 || //delete
  10.                 charCode == 13)   //enter key
  11.            {
  12.                return true;
  13.            }
  14.            else if (charCode >= 37 && charCode <= 40) //arrow keys
  15.            {
  16.                return true;
  17.            }
  18.            else if (charCode >= 48 && charCode <= 57) //0-9 on key pad
  19.            {
  20.                return true;
  21.            }
  22.            else if (charCode >= 96 && charCode <= 105) //0-9 on num pad
  23.            {
  24.                return true;
  25.            }
  26.            else
  27.                return false;
  28.  
  29.        } //end:NumericTextBox function
  30.    </script>

Now we will see how to validate the ASP.NET DropDownList control. Basically, we may require to validate that the user has selected some option in the DropDownList! Check the below code snippet on how to do it!

Validating DropDownList
  1. <div>
  2.    <label style="float:left;" >Quantity:</label>
  3.        <asp:DropDownList runat="server" ID="dropdownlist">
  4.            <asp:ListItem Text="Select" Value="Select"  />
  5.            <asp:ListItem Text="One" Value="One"  />
  6.            <asp:ListItem Text="Two" Value="Two"  />
  7.            <asp:ListItem Text="Three" Value="Three"  />
  8.        </asp:DropDownList>
  9.    </div>
  10.    <div>
  11.     <asp:Button runat="server" Text="Submit" OnClientClick="return Validate_ddl();" />
  12.    </div>
  13.  
  14.    <script type="text/javascript">
  15.        function Validate_ddl() {
  16.            var ddl = document.getElementById("<%=dropdownlist.ClientID %>");
  17.  
  18.            if (ddl.selectedIndex <= 0) {
  19.                alert('please select!');
  20.                return false;
  21.            }
  22.            else
  23.                return true;
  24.            
  25.        }
  26.    </script>

Finally, we will see how to validate ASP.NET Checkboxlist! We have a bunch of options displayed as checkbox, which we we may have to validate that user selects at least one checkbox! Check the below code on how do it!

Validating CheckBoxList
  1. <div>
  2.       <label style="float:left;">Skills:</label>
  3.       <asp:CheckBoxList runat="server" ID="checkboxlist">
  4.           <asp:ListItem Text="ASP.NET" Value="ASP.NET" />
  5.           <asp:ListItem Text="JAVA" Value="JAVA" />
  6.           <asp:ListItem Text="SQL SERVER" Value="SQL SERVER" />
  7.       </asp:CheckBoxList>
  8.   </div>
  9.  
  10.   <div>
  11.     <asp:Button runat="server" Text="Submit" OnClientClick="return Validate_checkboxlist();" />
  12.    </div>
  13.  
  14.  
  15.     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;
  16.         function Validate_checkboxlist() {
  17.             var isSkillsSelected = false;
  18.             $('input[type=checkbox]', '#' + '<%=checkboxlist.ClientID %>').each(function () {
  19.                 if (this.checked) {
  20.                     isSkillsSelected = true;
  21.                 }
  22.             });
  23.  
  24.             if (!isSkillsSelected)
  25.                 alert("Please select skills!");
  26.  
  27.         }
  28.     </script>

Now, we will see how to validate the ASP.NET File Upload control! Suppose you may have to allow users to select certain file types. Check the below code on how to do it!

Validating FileUpload
  1. <div>
  2.         <asp:FileUpload runat="server" ID="fileUpload" />
  3.     </div>
  4.     <div>
  5.  
  6.         <input type="button" name="name" value="Submit" onclick="return fileUpload_Validate();" />
  7.     </div>
  8.  
  9.     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;
  10.         
  11.         var AllowedFileTypes = new Array();
  12.         
  13.         AllowedFileTypes.push(".jpg"); //JPEG File Type
  14.         AllowedFileTypes.push(".bmp"); //BMP File Type
  15.         AllowedFileTypes.push(".gif"); //GIF File Type
  16.         AllowedFileTypes.push(".png"); //PNG File Type
  17.  
  18.         function fileUpload_Validate() {
  19.  
  20.             var bIsValidFile = false;
  21.  
  22.             try {
  23.  
  24.                 //———————————————————–
  25.                 //Below are the two version of retrieving the value from FileUpload
  26.                 //control. You can use any one of them, based on your requirement
  27.                 //jQuery version
  28.                 var filePath = new String($('#' + '<%=fileUpload.ClientID %>').val());
  29.  
  30.                 //JavaScript version
  31.                 var filePath = new String(document.getElementById('<%=fileUpload.ClientID %>').value);
  32.                 //———————————————————–
  33.  
  34.  
  35.                 //Throw error, if file is not selected!
  36.                 if (filePath.length <= 0) {
  37.                     alert("Please select a file!");
  38.                     return false;
  39.                 }
  40.  
  41.                 //Get the file extension from the selected path!
  42.                 var fileType = filePath.substring(filePath.lastIndexOf("."), filePath.length);
  43.  
  44.                 for (var x = 0; x < AllowedFileTypes.length; x++) {
  45.                     if (AllowedFileTypes[x] == fileType) {
  46.                         bIsValidFile = true;
  47.                         break;
  48.                     }
  49.                 }
  50.  
  51.                 if (!bIsValidFile) {
  52.                     alert('please select a valid file!');
  53.                 }
  54.                 return bIsValidFile;
  55.  
  56.             }
  57.             catch (e) {
  58.                 console.log('An Internal error has occured!');
  59.             }
  60.         }
  61.     </script>

Happy Web Programming!!!

5 Comments

  1. Howdy! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone4. I’m trying to find a template or plugin that might be able
    to correct this issue. If you have any suggestions, please share.

    Cheers!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s