This article shows how to apply validation on a TextBox, CheckBox, RadioButtin in ASP.NET C# using jQuery.
Here in this example I am using a registration form and on button click I am validating all the controls. The following is my aspx code:
- <%@ 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>Validation Using jQuery</title>
-
- <script src="jquery-1.8.2.js" type="text/javascript"></script>
-
- <script type="text/javascript">
- $(function() {
- $('#btnSubmit').click(function() {
- if ($("#txtName").val().length === 0) {
- alert('Please enter name.')
- return false;
- }
-
- if ($("#txtEmail").val().length === 0) {
- alert('Please enter Email.')
- return false;
- }
-
- var IsGenderSelect = false;
- $('.Gender').each(function() {
-
- if ($(this).find('input[type="radio"]:checked').length == 1) {
- IsGenderSelect = true;
- }
- });
-
- if (!IsGenderSelect) {
- alert('Please select gender.')
- return false;
- }
-
-
- if (!$('#chkTermsConditions').is(':checked')) {
- alert('Please accept Terms & Conditions')
- return false;
- }
- })
- });
- </script>
-
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table cellpadding="5" cellspacing="5" width="70%" align="center" style="background-color: SkyBlue;">
- <tr>
- <td align="center" colspan="2" style="background-color: Green; font-weight: bold;
- font-size: 14pt; color: Blue; font-family: Arial;">
- Registration Form
- </td>
- </tr>
- <tr>
- <td align="right" width="40%">
- Name #:
- </td>
- <td>
- <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td align="right">
- Email #:
- </td>
- <td>
- <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td align="right">
- Sex #:
- </td>
- <td>
- <asp:RadioButton ID="rdbMale" runat="server" Text="Male" GroupName="Gender" CssClass="Gender" />
- <asp:RadioButton ID="rdbFemale" runat="server" Text="Female" GroupName="Gender" CssClass="Gender" />
- </td>
- </tr>
- <tr>
- <td>
- <td>
- <asp:CheckBox ID="chkTermsConditions" runat="server" Text="Terms & Conditions" />
- </td>
- </td>
- </tr>
- <tr>
- <td>
- </td>
- <td>
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Now Run the application
If you don't enter something into text boxes:
Image 1
Image 2
If you don't select gender:
Image 3
If you don't accept Terms & Conditions:
Image 4
Image 5