Please disable your adblock and script blockers to view this page
 

Server side validation code for Asp.Net TextBox,DropDownList,CheckBoxList,RadioButtonList,ListBox,CheckBox and RadioButton controls

Introduction: In this article i am going to explain how to validate asp.net controls e.g. TextBox, CheckBox, RadioButton, DropDownList, CheckBoxList, RadioButtonList and ListBox through code i.e. server side validation  in Asp.net using both C# and VB language code.

Description: First of all the question arise What is the difference between client-side and server-side validations?

Answer is:
  • Client-side validations take place at the client side with the help of JavaScript and jQuery etc before the Web page is sent to the server whereas server-side validations take place at the server end and done using programming languages like C#.Net,VB.Net etc.
  • Client-side validation is faster than server-side because it takes place on client side (on browser) and the networking time from client to server is saved, whereas the server-side validation is done on the web server and server renders the data into html page and sends back to the client (browser).  Thus it is bit slower.
  • Client side validation can be bypassed by disabling the browser's JavaScript, so we should also validate on the server side because it protects against the malicious user, who can easily bypass our JavaScript and submit dangerous input to the server.
Implementation:  Let's create a sample web page to demonstrate the server side validation of asp.net controls.

<%@ 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></title>
    <style type="text/css">
        .error
        {
            border: 1px solid red;
        }
        .errorstyle
        {
            font-size: 16px;
            line-height: 22px;           
        }
     
        .errorstyle ul li
        {
            margin-left: 5px;
            color: #ff0000;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width:300px;">
        <fieldset>
            <legend>Validate TextBox</legend>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        </fieldset>
        <fieldset>
            <legend>Validate DropDownList</legend>
            <asp:DropDownList ID="DropDownList1" runat="server" Width="150px">
                <asp:ListItem Value="0" Text="--Select--"></asp:ListItem>
                <asp:ListItem Value="1" Text="Asp.Net"></asp:ListItem>
                <asp:ListItem Value="2" Text="MVC"></asp:ListItem>
                <asp:ListItem Value="3" Text="C#"></asp:ListItem>
                <asp:ListItem Value="4" Text="jQuery"></asp:ListItem>
            </asp:DropDownList>
        </fieldset>
        <fieldset>
            <legend>Validate CheckBox</legend>
            <asp:CheckBox ID="CheckBox1" runat="server" Text="Married" />
        </fieldset>
        <fieldset>
            <legend>Validate CheckBoxList</legend>
            <asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatColumns="2">
                <asp:ListItem Value="1" Text="Asp.Net"></asp:ListItem>
                <asp:ListItem Value="2" Text="MVC"></asp:ListItem>
                <asp:ListItem Value="3" Text="C#"></asp:ListItem>
                <asp:ListItem Value="4" Text="jQuery"></asp:ListItem>
            </asp:CheckBoxList>
        </fieldset>
        <fieldset>
            <legend>Validate RadioButton</legend>
            <asp:RadioButton ID="RadioButton1" runat="server" Text="Married" />
        </fieldset>
        <fieldset>
            <legend>Validate RadioButtonList</legend>
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatColumns="2">
                <asp:ListItem Value="1" Text="Asp.Net"></asp:ListItem>
                <asp:ListItem Value="2" Text="MVC"></asp:ListItem>
                <asp:ListItem Value="3" Text="C#"></asp:ListItem>
                <asp:ListItem Value="4" Text="jQuery"></asp:ListItem>
            </asp:RadioButtonList>
        </fieldset>
        <fieldset>
            <legend>Validate ListBox</legend>
            <asp:ListBox ID="ListBox1" runat="server" Width="150px">
                <asp:ListItem Value="1" Text="Asp.Net"></asp:ListItem>
                <asp:ListItem Value="2" Text="MVC"></asp:ListItem>
                <asp:ListItem Value="3" Text="C#"></asp:ListItem>
                <asp:ListItem Value="4" Text="jQuery"></asp:ListItem>
            </asp:ListBox>
        </fieldset>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
        <div class="errorstyle" >
            <asp:Literal ID="ltrlErrorMsg" runat="server"></asp:Literal>
        </div>
    </div>
    </form>
</body>

Asp.Net C# Code to validate controls server side

using System.Text;

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (IsControlsValid())
        {
            // Form is validated. Write your submit button code here.
        }    
    }

    private bool IsControlsValid()
    {
        bool isValid = true;
        StringBuilder sb = new StringBuilder();
        sb.Append("<ul>");       

        //Validate TextBox(can't be left empty)
        if (String.IsNullOrEmpty(txtName.Text.Trim()))
        {
            isValid = false;
            txtName.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please enter in TextBox"));
        }
        else
        {
            txtName.CssClass = "";
        }

        //Validate DropDownList(Item must be selected)
        if (DropDownList1.SelectedValue == "0")
        {
            isValid = false;
            DropDownList1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select DropDowlist item"));
        }
        else
        {
            DropDownList1.CssClass = "";
        }
        
        //Validate CheckBox(Must be checked)
        if (!CheckBox1.Checked)
        {
            isValid = false;
            CheckBox1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select Checkbox"));
        }
        else
        {
            CheckBox1.CssClass = "";
        }

        //Validate RadioButton(Must be selected)
        if (!RadioButton1.Checked)
        {
            isValid = false;
            RadioButton1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select RadioButton"));
        }
        else
        {
            RadioButton1.CssClass = "";
        }

        //Validate CheckBoxList(At least one item must be selected)
        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (item.Selected)
            {
                isValid = true;
                break;
            }
            else
            {
                isValid = false;
            }
        }
        if (isValid == false)
        {
            CheckBoxList1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one option from CheckBoxList"));
        }
        else
        {
            CheckBoxList1.CssClass = "";
        }

        //Validate RadioButton(Item must be selected)
        foreach (ListItem item in RadioButtonList1.Items)
        {
            if (item.Selected)
            {
                isValid = true;
                break;
            }
            else
            {
                isValid = false;
            }
        }
        if (isValid == false)
        {
            RadioButtonList1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one option from RadioButtonList"));
        }
        else
        {
            RadioButtonList1.CssClass = "";
        }
       
        //Validate ListBox (Item must be selected)
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
            {
                isValid = true;
                break;
            }
            else
            {
                isValid = false;
            }
        }
        if (isValid == false)
        {
            ListBox1.CssClass = "error";
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one item from ListBox"));
        }
        else
        {
            ListBox1.CssClass = "";
        }
     
        sb.Append("</ul>");       
        ltrlErrorMsg.Text = sb.ToString();
        return isValid;
    }


Asp.Net VB Code to validate controls server side

Imports System.Text

    Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
        If IsControlsValid() Then
            ' Form is validated. Write your submit button code here.
        End If
    End Sub

    Private Function IsControlsValid() As Boolean
        Dim isValid As Boolean = True
        Dim sb As New StringBuilder()
        sb.Append("<ul>")

        'Validate TextBox(Can't be left empty)
        If (String.IsNullOrEmpty(txtName.Text.Trim())) Then
            isValid = False
            txtName.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please enter in TextBox"))
        Else
            txtName.CssClass = ""
        End If

        'Validate DropDownList(Item must be selected)
        If DropDownList1.SelectedValue = "0" Then
            isValid = False
            DropDownList1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select DropDowlist item"))
        Else
            DropDownList1.CssClass = ""
        End If

        'Validate CheckBox(Must be checked)
        If Not CheckBox1.Checked Then
            isValid = False
            CheckBox1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select Checkbox"))
        Else
            CheckBox1.CssClass = ""
        End If

        'Validate RadioButton(Must be selected)
        If Not RadioButton1.Checked Then
            isValid = False
            RadioButton1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select RadioButton"))
        Else
            RadioButton1.CssClass = ""
        End If

        'Validate CheckBoxList(At least one item must be selected)
        For Each item As ListItem In CheckBoxList1.Items
            If item.Selected Then
                isValid = True
                Exit For
            Else
                isValid = False
            End If
        Next
        If isValid = False Then
            CheckBoxList1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one option from CheckBoxList"))
        Else
            CheckBoxList1.CssClass = ""
        End If

        'Validate RadioButton(Item must be selected)
        For Each item As ListItem In RadioButtonList1.Items
            If item.Selected Then
                isValid = True
                Exit For
            Else
                isValid = False
            End If
        Next
        If isValid = False Then
            RadioButtonList1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one option from RadioButtonList"))
        Else
            RadioButtonList1.CssClass = ""
        End If

        'Validate ListBox (Item must be selected)
        For Each item As ListItem In ListBox1.Items
            If item.Selected Then
                isValid = True
                Exit For
            Else
                isValid = False
            End If
        Next
        If isValid = False Then
            ListBox1.CssClass = "error"
            sb.Append(String.Format("<li>{0}</li>", "Please select at least one item from ListBox"))
        Else
            ListBox1.CssClass = ""
        End If

        sb.Append("</ul>")
        ltrlErrorMsg.Text = sb.ToString()
        Return isValid
    End Function


Now over to you:
" I hope you have learned how to validate asp.net controls server side using code with this example and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon