Showing posts with label validations. Show all posts
Showing posts with label validations. Show all posts

Sep 20, 2013

Back end scripting, front end scripting what is the difference between two?



Or
Client side validation and server side validations
Or
Which type of validations is better or best? Server side validation or Client side Validation?

Validations can be performed on the server side or on the client side ( web browser). The user input validation take place on the Server Side during a post back session is called Server Side Validation and the user input validation take place on the Client Side (web browser) is called Client Side Validation. Client Side Validation does not require a postback. If the user request requires server resources to validate the user input, you should use Server Side Validation. If the user request does not require any server resources to validate the input, you can use Client Side Validation.




Server Side Validation
In the Server Side Validation, the input submitted by the user is being sent to the server and validated using one of server side scripting languages such as ASP.Net, PHP etc. After the validation process on the Server Side, the feedback is sent back to the client by a new dynamically generated web page. It is better to validate user input on Server Side because you can protect against the malicious users, who can easily bypass your Client Side scripting language and submit dangerous input to the server.
For example, if the user enters an email, you can show an error message after click the button has to check in in the database not immediately so the user can enter unique every field before they submit the form.

Client Side Validation
In the Client Side Validation you can provide a better user experience by responding quickly at the browser level. When you perform a Client Side Validation, all the user inputs validated in the user's browser itself. Client Side validation does not require a round trip to the server, so the network traffic which will help your server perform better. This type of validation is done on the browser side using script languages such as JavaScript, VBScript or HTML5 attributes.
For example, if the user enters an invalid email format, you can show an error message immediately before the user move to the next field, so the user can correct every field before they submit the form.
Mostly the Client Side Validation depends on the JavaScript Language, so if users turn JavaScript off, it can easily bypass and submit dangerous input to the server . So the Client Side Validation cannot protect your application from malicious attacks on your server resources and databases.
As both the validation methods have their own significances, it is recommended that the Server side validation is more SECURE!


Apr 27, 2011

Asp.Net ListBox CustomValidator

Hi folksMy objective there was to have a custom validating function to test if a listbox was empty.

<asp:ListBox ID=”lBox” SelectionMode=”Multiple” runat=”server” Width=”150px”></asp:ListBox>
The validator
<asp:CustomValidator ID=”cv1″ ErrorMessage=”The list box is empty” OnServerValidate=”cv1_ServerValidate” Display=”Dynamic” SetFocusOnError=”True” ControlToValidate=”lBox” ValidateEmptyText=”true” runat=”server” ClientValidationFunction=”ListBoxValid”></asp:CustomValidator>

I just spent around 20 minutes trying to understand WHY my custom validation client script function
was not working for my listbox. And here is the final solution.
My major mistake was to not include the ValidateEmptyText=”true” directive in my custom validating control. This was causing the CustomValidatorEvaluateIsValid Microsoft function to return true if the
 listbox was empty.
Here’s the code
First the javascript function
function ListBoxValid(sender, args) {
args.IsValid = document.getElementById(sender.controltovalidate).options.length>0;
}
The listbox


A dummy button
<asp:Button ID=”btnTest” runat=”server” Text=”Button” CausesValidation=”true” />
And the server side function, just in case
protected void cv1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = lBox.Items.Count > 0;
}
I hope that this will help many of you ;)

Tested under IE7 && FF3

SERVER SIDE VALIDATION:

<asp:CustomValidator ID="cv1" ErrorMessage="Select Group Name" OnServerValidate="cv1_ServerValidate" Display="Dynamic" SetFocusOnError="true" ControlToValidate="lstSelGName_Sel" ValidateEmptyText="true" runat="server" ClientValidationFunction="ListBoxValid"></asp:CustomValidator>



cv1_ServerValidate(object source, ServerValidateEventArgs args)

protected void
{
if (lstSelGName_Sel.Items.Count > 0)
args.IsValid = true;
else
args.IsValid = true;
}

Jul 30, 2010

ASP.NET validation summary Control(value)

<html>
<body>

<form runat="server">
<table>
<tr>
<td>
<table bgcolor="#b0c4de" cellspacing="10">
   <tr>
     <td align="right">Name:</td>
     <td><asp:TextBox id="txt_name" runat="server"/></td>
     <td>
     <asp:RequiredFieldValidator
     ControlToValidate="txt_name"
     ErrorMessage="Name"
     Text="*"
     runat="server"/>
     </td>
   </tr>
   <tr>
     <td align="right">Card Type:</td>
     <td>
     <asp:RadioButtonList id="rlist_type"
     RepeatLayout="Flow"
     runat="server">
     <asp:ListItem>Diners</asp:ListItem>
     <asp:ListItem>MasterCard</asp:ListItem>
     <asp:ListItem>Visa</asp:ListItem>
     </asp:RadioButtonList>
     </td>
     <td>
     <asp:RequiredFieldValidator
     ControlToValidate="rlist_type"
     ErrorMessage="Card Type"
     InitialValue=""
     Text="*"
     runat="server"/>
     </td>
   </tr>
   <tr>
     <td></td>
     <td><asp:Button id="b1" Text="Submit" runat="server"/></td>
     <td></td>
   </tr>
</table>
</td>
</tr>
</table>
<br />
<asp:ValidationSummary
HeaderText="You must enter a value in the following fields:"
DisplayMode="BulletList"
EnableClientScript="true"
runat="server"/>
</form>

</body>
</html>



Output Result:


Name: *
Card Type:




You must enter a value in the following fields:
  • Name

ASP.NET regularexpression validation Control

<html>
<body>

<form runat="server">
Enter a US zip code:
<asp:TextBox id="txtbox1" runat="server" />
<br /><br />
<asp:Button text="Submit" OnClick="submit" runat="server" />
<br /><br />
<asp:Label id="lbl" runat="server" />
<br />
<asp:RegularExpressionValidator
ControlToValidate="txtbox1"
ValidationExpression="\d{5}"
EnableClientScript="false"
ErrorMessage="The zip code must be 5 numeric digits!"
runat="server" />
</form>

</body>
</html>



Output Result:

Enter a US zip code:



The page is not valid!
The zip code must be 5 numeric digits!

ASP.NET custom validation Control

<script  runat="server">
Sub user(source As object,args As ServerValidateEventArgs)
   if len(args.Value)<8 or len(args.Value)>16 then
    args.IsValid=false
   else
    args.IsValid=true
   end if
End Sub
</script>
    

<html>
<body>

<form runat="server">
<asp:Label runat="server" Text="Enter a username: " />
<asp:TextBox id="txt1" runat="server" />
<asp:Button Text="Submit" runat="server"/>
<br />
<asp:Label id="mess" runat="server"/>
<br />
<asp:CustomValidator
ControlToValidate="txt1"
OnServerValidate="user"
Text="A username must be between 8 and 16 characters!"
runat="server"/>
</form>

</body>
</html>


Output Result:

Enter a username:

A username must be between 8 and 16 characters!

ASP.NET comapre validation Control(value)

<html>
<body>

<form runat="server">
<table border="0" bgcolor="#b0c4de">
   <tr valign="top">
     <td colspan="4"><h4>Compare two values</h4></td>
   </tr>
   <tr valign="top">
     <td><asp:TextBox id="txt1" runat="server" /></td>
     <td> = </td>
     <td><asp:TextBox id="txt2" runat="server" /></td>
     <td><asp:Button Text="Validate" runat="server" /></td>
   </tr>
</table>
<br />
<asp:CompareValidator
id="compval"
Display="dynamic"
ControlToValidate="txt1"
ControlToCompare="txt2"
ForeColor="red"
BackColor="yellow"
Type="String"
EnableClientScript="false"
Text="Validation Failed!"
runat="server" />
</form>

</body>
</html>



o/p:

Compare two values

=

Validation Failed!

ASP.NET RangeValidator Control

<html>
<body>

<form runat="server">
Enter a date between 2005-01-01 and 2005-12-31:
<br />
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
<br /><br />
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="2005-01-01"
MaximumValue="2005-12-31"
Type="Date"
EnableClientScript="false"
Text="The date must be between 2005-01-01 and 2005-12-31!"
runat="server" />
</form>

</body>
</html>





Enter a date between 2005-01-01 and 2005-12-31:




The date must be between 2005-01-01 and 2005-12-31!

Jun 21, 2010

JQuery Example For validations

<%@ 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>JQuery Example www.dotnetspark.com</title>
<style type="text/css">
label.error { color: red; vertical-align: top; }
    .style1
    {
        font-size: xx-large;
        font-weight: bold;
    }
</style>

     <script type="text/javascript" src="script/jquery-1.3.2.js"></script>
     <script type="text/javascript" src="script/jquery.validate.js"></script>
   <script type="text/javascript">
        $(document).ready(function() {
            $("#form1").validate({
                rules: {
                    <%=txtUserName.UniqueID %>: {
                        minlength: 5,
                        required: true
                    },
                    <%=txtPassword.UniqueID %>: {
                        minlength: 5,
                        required: true
                    },
                    <%=txtEmail.UniqueID %>: {
                        required: true
                    },
                    <%=txtURL.UniqueID %>: {
                     required: true
                    }
                }, messages: {
                    <%=txtUserName.UniqueID %>:{
                        required: "Plaese Enter your username",
                        minlength: "User name must be atleaet of 5 characters"
                    },
                     <%=txtPassword.UniqueID %>:{
                        required: "Plaese Enter your password",
                        minlength: "Password must be atleaet of 5 characters"
                    },
                     <%=txtEmail.UniqueID %>:{
                        required: "Plaese Enter your Email Id",
                     
                    },
                     <%=txtURL.UniqueID %>:{
                        required: "Plaese Enter Website URL",
                     
                    }
                   
                   
               }
            });
        });
    </script>
 
</head>

<body>
 

    <form id="form1" runat="server">

    <table style="width:100%;">
        <tr>
            <td colspan="3" align="center" class="style1">
                JQuery Validation Example</td>
          
        </tr>
        <tr>
            <td colspan="2" align="center">
                &nbsp;</td>
          
        </tr>
        <tr>
            <td align="right">
                <asp:Label ID="lblUserName" runat="server" Text="User Name :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" Width="230px"></asp:TextBox>
            </td>
           
        </tr>
        <tr>
            <td align="right">
                <asp:Label ID="lblPassword" runat="server" Text="Password :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server"  TextMode="Password" Width="230px"></asp:TextBox>
            </td>
           
        </tr>
        <tr>
            <td align="right">
                <asp:Label ID="lblEmail" runat="server" Text="Email Id :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" CssClass="email" runat="server"
                    Width="230px"></asp:TextBox>
            </td>
          
        </tr>
        <tr>
            <td align="right">
                <asp:Label ID="lblURL" runat="server" Text="URL :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtURL" CssClass="url" runat="server" Width="230px"></asp:TextBox>
            </td>
           
        </tr>
        <tr>
            <td align="right">
                &nbsp;</td>
            <td>
                &nbsp;</td>
           
        </tr>
        <tr>
            <td align="right">
                &nbsp;</td>
            <td>
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
            </td>
          
        </tr>
    </table>
    </form>
</body>
</html>

Registration form validation using jQuery

by Developer 1. March 2010 05:28 Mainly we will use javascript for validating the several fields of our webpage. For example we have registration page with several fields like username, mobile number, email, date of birth and gender. We have to handle each filed validation in a different way. Here we are going to learn how to validate simple textbox, radio button and checkbox.

jQuery provides us simple way to validate each filed. Here I am explaining validation procedure for each filed.
Below is the code to validate our simple registration form fields.

<html>
    <head>
        <title>validating the registration form fields using jQuery</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#btn_submit').click(function(event) {

                //validating username
                    if ($('#user_name').val().length < 1) {
                        alert('Please enter user name');
                        $('#user_name').focus();
                        return false;
                    }
                    if (!is_username($('#user_name').val())) {
                        alert('Please enter valid user name');
                        $('#user_name').focus();
                        return false;
                    }
                    function is_username(uname) {
                        var pattern = new RegExp(/^[a-z0-9_]+$/);
                        return pattern.test(uname);
                    }

                    //validating mobile number
                    if ($('#mobile_number').val().length < 1) {
                        alert('Please enter your mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    if ((!is_mobile($('#mobile_number').val())) || ($('#mobile_number').val().length < 10)) {
                        alert('Please enter valid mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    function is_mobile(mobile) {
                        var pattern = new RegExp(/^[0-9]+$/);
                        return pattern.test(mobile);
                    }

                    //validating email address
                    if ($('#email_id').val().length < 1) {
                        alert('Please enter your Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    if (!is_email($('#email_id').val())) {
                        alert('Please enter valid Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    function is_email(emailid) {
                        var pattern = new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
                        return pattern.test(emailid);
                    }


                    //validating date of birth
                    if ($('#dob').val().length < 1) {
                        alert('Please enter your Date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    if (!is_dob($('#dob').val())) {
                        alert('Please enter valid date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    function is_dob(dob) {
                        var pattern = new RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);
                        return pattern.test(dob);
                    }

               //validating gender
               if ($("input[name='rdgender']:checked").val() != 'M' && $("input[name='rdgender']:checked").val() != 'F') {
                        alert('Please select your gender');
                        return false;
                    }

                    //validating checkbox
                    if ($('#chk_tc:checked').val() == null) {
                        alert('Please agree terms and conditions');
                        return false;
                    }

                });
            });   
        </script>
    </head>
    <body>
        <div style="margin-left:300px;">
        <label>User Name</label><input type="text" id="user_name"/><br/><br/>
        <label>Mobile Number</label><input type="text" id="mobile_number"/><br/><br/>
        <label>Email Id</label><input type="text" id="email_id"/><br/><br/>
        <label>Date Of Birth</label><input type="text" id="dob"/><br/><br/>
        <label>Gender</label>
            <table id="rdgender" border="0">
                            <tbody>
                            <tr>
                                <td>
                                    <input id="rdgender_0" name="rdgender" value="M" type="radio"/>
                                    <label for="rdgender_0">Male</label>

                                </td>
                                <td>
                                    <input id="rdgender_1" name="rdgender" value="F" type="radio"/>
                                    <label for="rdgender_1">Female</label>
                                </td>
                             </tr>
                           </tbody>
                          </table>   
            <br/><br/>           
       <input type="checkbox" id="chk_tc"/><label>I agree the Terms & Condition</label><br/><br/>
      <input type="submit" id="btn_submit" value="Submit"/>
        </div>       
    </body>
 </html>

In the above example we have simple registration form with several fields like username, mobile number, email, date of birth and gender. We will discuss validation procedure for each field separately.

In the first step we bind the our validation function for submit button through click event using  $('#btn_submit').click(function(event) {. Inside this function we define the validation methods for each filed

Validating the user name field:

                        //validating username
                    if ($('#user_name').val().length < 1) {
                        alert('Please enter user name');
                        $('#user_name').focus();
                        return false;
                    }
                    if (!is_username($('#user_name').val())) {
                        alert('Please enter valid user name');
                        $('#user_name').focus();
                        return false;
                    }
                    function is_username(uname) {
                        var pattern = new RegExp(/^[a-z0-9_]+$/);
                        return pattern.test(uname);
                    }

By using above code we are validating the user name filed. It is simple textbox, first we are checking whether user entered anything in the user name field or not by checking its length. After that we are restricting the user to enter only alphabetic, underscore(_) and numbers within the user name filed by passing user name field value o the RegExp(/^[a-z0-9_]+$/);

Validating mobile number:

                   //validating mobile number
                    if ($('#mobile_number').val().length < 1) {
                        alert('Please enter your mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    if ((!is_mobile($('#mobile_number').val())) || ($('#mobile_number').val().length < 10)) {
                        alert('Please enter valid mobile number');
                        $('#mobile_number').focus();
                        return false;
                    }
                    function is_mobile(mobile) {
                        var pattern = new RegExp(/^[0-9]+$/);
                        return pattern.test(mobile);
                    }

For the mobile number field, we have to allow only numbers and length should be minimum of 10.

Validating Email Id:

                   //validating email address
                    if ($('#email_id').val().length < 1) {
                        alert('Please enter your Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    if (!is_email($('#email_id').val())) {
                        alert('Please enter valid Email Id');
                        $('#email_id').focus();
                        return false;
                    }
                    function is_email(emailid) {
                        var pattern = new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
                        return pattern.test(emailid);
                    }

There are some specific conditions for email id like email id must have @ and .(dot).  We are validating the Email Id by using RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);

Validating the date of birth:

                    //validating date of birth
                    if ($('#dob').val().length < 1) {
                        alert('Please enter your Date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    if (!is_dob($('#dob').val())) {
                        alert('Please enter valid date of birth');
                        $('#dob').focus();
                        return false;
                    }
                    function is_dob(dob) {
                        var pattern = new RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);
                        return pattern.test(dob);
                    }

By using above code we are validating the date of birth. Date of birth must be like dd/mm/yy(day/month/year). We are validating the date of birth field by using  RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);

Validating the radio button (gender):

           //validating gender
           if ($("input[name='rdgender']:checked").val() != 'M' && $("input[name='rdgender']:checked").val() != 'F') {
                        alert('Please select your gender');
                        return false;
                    }

We have two radio buttons to ask user about his gender. We are validating radio buttons based on user input. We can validate radio button, that means gender field by comparing its value using $("input[name='rdgender']:checked").val(). It should be "M" or "F".

Validating checkbox:

                   //validating checkbox
                    if ($('#chk_tc:checked').val() == null) {
                        alert('Please agree terms and conditions');
                        return false;
                    }

At the end of your registration form, you need to have terms & conditions. User must accept your terms & conditions. Here you have checkbox, user must check the checkbox. You can validate checkbox by using its value $('#chk_tc:checked').val(). It should not be null.

In this way you can easily validate your registration form by using jQuery javascript functions.

May 11, 2010

Client-Side Validation for the CheckBoxes Inside a GridView

<%@ 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>Selecting a Checkbox</title>

    <script type="text/javascript">
        var TargetBaseControl = null;
       
        window.onload = function()
        {
            try
            {
                //get target base control.
                TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
            }
            catch(err)
            {
                TargetBaseControl = null;
            }
        }
       
        function TestCheckBox()
        {             
            if(TargetBaseControl == null) return false;
            //get target child control.
            var TargetChildControl = "chkBxSelect";
           
            //get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");
           
            for(var n = 0; n < Inputs.length; ++n)
                if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0 && Inputs[n].checked)
                    return true;                
           
            alert('Select at least one checkbox!');
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField HeaderText="n" DataField="sno">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkBxSelect" runat="server" />
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="btnPost" runat="server" Text="Post" OnClientClick="javascript:return TestCheckBox();"
            OnClick="btnPost_Click" />
        <hr />
        <asp:Label ID="lblMsg" runat="server" Font-Bold="True" ForeColor="Red" Width="268px"></asp:Label>
    </form>
</body>
</html>



code:

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)
    {       
        if (!IsPostBack)
        {
            GridView1.DataSource = GetDataSource();
            GridView1.DataBind();
        }
    }

    protected DataTable GetDataSource()
    {
        DataTable dTable = new DataTable();
        DataRow dRow = null;
        Random rnd = new Random();
        dTable.Columns.Add("sno");

        for (int n = 0; n < 10; ++n)
        {
            dRow = dTable.NewRow();

            dRow["sno"] = n + ".";

            dTable.Rows.Add(dRow);
            dTable.AcceptChanges();
        }

        return dTable;
    }
    protected void btnPost_Click(object sender, EventArgs e)
    {
        lblMsg.Text = "Form is posted!";
    }
}