Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Sunday, 1 March 2015

Client side validation is best option for input validation, but if Javascript of browser is disable then client side validation will not work. In that case server side validation is needed. We must use both type of validations.

In this article I will explain how to validate asp.net controls e.g. TextBox, CheckBox, RadioButton, DropDownList, CheckBoxList, RadioButtonList and ListBox through code i.e. server sidevalidation  in Asp.net using both C# and VB language code.

What is the difference between client-side and server-side validations?
 Client-side validations means validation using JavaScript and jQuery 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.
  1. 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.
  2. Client side validation can be bypassed by disabling the browser's JavaScript. Server side validation is more secure because these checks cannot be easily bypassed.

Source Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Validate-server-side.aspx.cs" Inherits="Validate_server_side" %>

<!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 id="Head1" 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 City--"></asp:ListItem>
                <asp:ListItem Value="1" Text="Chandigarh"></asp:ListItem>
                <asp:ListItem Value="2" Text="Ambala"></asp:ListItem>
                <asp:ListItem Value="3" Text="Panchkula"></asp:ListItem>
                <asp:ListItem Value="4" Text="Shimla"></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="Chandigarh"></asp:ListItem>
                <asp:ListItem Value="2" Text="Ambala"></asp:ListItem>
                <asp:ListItem Value="3" Text="Panchkula"></asp:ListItem>
                <asp:ListItem Value="4" Text="Shimla"></asp:ListItem>
            </asp:CheckBoxList>
        </fieldset>
        <fieldset>
            <legend>Validate RadioButton</legend>
            <asp:RadioButton ID="RadioButton1" runat="server" Text="Indian" />
        </fieldset>
        <fieldset>
            <legend>Validate RadioButtonList</legend>
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatColumns="2">
 <asp:ListItem Value="1" Text="Chandigarh"></asp:ListItem>
                <asp:ListItem Value="2" Text="Ambala"></asp:ListItem>
                <asp:ListItem Value="3" Text="Panchkula"></asp:ListItem>
                <asp:ListItem Value="4" Text="Shimla"></asp:ListItem>
            </asp:RadioButtonList>
        </fieldset>
        <fieldset>
            <legend>Validate ListBox</legend>
            <asp:ListBox ID="ListBox1" runat="server" Width="150px">
                <asp:ListItem Value="1" Text="Chandigarh"></asp:ListItem>
                <asp:ListItem Value="2" Text="Ambala"></asp:ListItem>
                <asp:ListItem Value="3" Text="Panchkula"></asp:ListItem>
                <asp:ListItem Value="4" Text="Shimla"></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>
</html>

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

0 comments:

Post a Comment