Friday, 28 September 2012

Validation Controls in ASP.net

ASP.Net provides validation controls which a rich amount
of validation services that saves your work to make
java script code because at a huge level java script is used to validate client side
validation. for perform validation using java script you must have knowledge of
java script.
But you can perform powerful validation using ASP.net Validation
Controls with knowledge of java script..

RequiredFieldValidator Control

Evaluates the value of an input control to ensure that the user enters a value.
Use the RequiredFieldValidator control to make an input control a mandatory field. The input control fails validation if the value it contains does not change from its initial value when validation is performed. This prevents the user from leaving the associated input control unchanged. By default, the initial value is an empty string (""), which indicates that a value must be entered in the input control for it to pass validation.

Controls :
  • Textbox
  • ASP Button
  • Requirefield Validater
  • Label
Property :
         RequiredFieldValidator
  • ControlToValidate="TextBox1"
  • ErrorMessage="*" 
Aspx page code 
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
<asp:Label ID="Label1" runat="server"></asp:Label> 
</form>

Server Side code :
protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Running Server code";
    }


RangeValidator Control 


Evaluates the value of an input control to determine whether it is between the specified upper and lower boundaries.
The RangeValidator control allows you to check whether a user's entry is between a specified upper and a specified lower boundary. You can check ranges within pairs of numbers, alphabetic characters, and dates. Boundaries are expressed as constants.


Use the ControlToValidate property to specify the input control to validate. The MinimumValue and MaximumValue properties specify the minimum and maximum values of the valid range, respectively.

The Type property is used to specify the data type of the values to compare. The values to compare are converted to this data type before any comparison is performed.

If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.


The RangeValidator control throws an exception if the value specified by the MaximumValue or MinimumValue property cannot be converted to the data type specified by the Type property. For example, when a RangeValidator control's Type property is set to "Currency", the MinimumValue and MaximumValue properties must be provided in a format such as that described in NumberFormatInfo..::.CurrencyDecimalDigits, otherwise an exception is thrown.



Controls :
  • TextBox
  • RangeValidator
  • ASP Button
  • Label
Property : 
     RangeValidator
  • ControlToValidate="TextBox1"
  • ErrorMessage="Please Enter Value between 1 to 100"
  • MaximumValue="100" MinimumValue="1"
aspx page code :
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
            ControlToValidate="TextBox1" ErrorMessage="Please Enter Value between 1 to 100"
            MaximumValue="100" MinimumValue="1"></asp:RangeValidator>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
 <asp:Label ID="Label1" runat="server"></asp:Label>
Server Side Code :
 protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Running Server code";
    }


Regular ExpressionValidator

The Regular Expression Editor enables you to edit the ValidationExpression property of the RegularExpressionValidator control. It offers several predefined formats, such as for telephone numbers and zip codes. You can also edit the format in the text box.






 Controls :
  • Textbox
  • RegularExpressionValidator
  • ASP Button
  • Label
Property Setting...
   RegularExpressionValidator
  • ControlToValidate="TextBox1"
  • ErrorMessage="Please Provide valid email. address"
  • ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
aspx page code..
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="TextBox1" ErrorMessage="Please Provide valid email. address"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
<asp:Label ID="Label1" runat="server"></asp:Label>
Server Side Code.... 
 protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Running Server code";
    }


CompareValidator

Evaluates the value of an input control against a constant value or the value of another input control to determine whether the two values match the relationship specified by a comparison operator (less than, equal to, greater than, and so on).


The CompareValidator control allows you to compare the value entered by the user into an input control, such as a TextBox control, with the value entered into another input control, or with a constant value. You can also use the CompareValidator control to determine whether the value entered into an input control can be converted to the data type specified by the Type property.

Specify the input control to validate by setting the ControlToValidate property. If you want to compare a specific input control with another input control, set the ControlToCompare property with the name of the control to compare.

Instead of comparing the values of two input controls, you can compare the value of an input control to a constant value. Specify the constant value to compare with by setting the ValueToCompare property.

The Operator property allows you to specify the type of comparison to perform, such as greater than, equal to, and so on. If you set the Operator property to ValidationCompareOperator.DataTypeCheck, the CompareValidator control ignores both the ControlToCompare and ValueToCompare properties and simply indicates whether the value entered into the input control can be converted to the data type specified by the Type property
 








Controls..
  • Textbox
  • CompareValidator
  • ASP Button
  • Label 
Property..
     CompareValidator
  • ControlToCompare="TextBox1"
  • ControlToValidate="TextBox2"
  • ErrorMessage="Password does not matched" 
aspx code..
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
 <asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
            ControlToCompare="TextBox1" ControlToValidate="TextBox2"
            ErrorMessage="Password does not matched"></asp:CompareValidator>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
 <asp:Label ID="Label1" runat="server"></asp:Label>

Code...
protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Running Server code";
    }
CustomValidator Control  

Evaluates the value of an input control to determine whether it passes customized validation logic.
 The CustomValidator control allows you to create a validation control with customized validation logic. For example, you can create a validation control that checks whether the value entered into a text box is an even number.

Validation controls always perform validation checking on the server. They also have complete client-side implementation that allows DHTML-supported browsers (such as Microsoft Internet Explorer 4.0 or later) to perform validation on the client. Client-side validation enhances the validation process by checking user input before it is sent to the server. This allows errors to be detected on the client before the form is submitted, avoiding the round-trip of information necessary for server-side validation.

To create a server-side validation function, provide a handler for the ServerValidate event that performs the validation. The string from the input control to validate can be accessed by using the Value property of the ServerValidateEventArgs object passed into the event handler as a parameter. The result of the validation is then stored in the IsValid property of the ServerValidateEventArgs object.

To create a client-side validation function, first add the server-side validation function described earlier. Next, add the client-side validation script function to the .aspx page.

If you are using Visual Basic, the function must be in the form:

Sub ValidationFunctionName (source, arguments)

If you are using JScript, the function must be in the form:

Function ValidationFunctionName (source, arguments)

Use the ClientValidationFunction property to specify the name of the client-side validation script function associated with the CustomValidator control. Because the script function is executed on the client, the function must be in a language that the target browser supports, such as Visual Basic or JScript.

Like server-side validation, using the Value property of the arguments parameter accesses the value to validate. Return the result of the validation by setting the IsValid property of the arguments parameter.

Security Note:
When creating a client-side validation function, make sure you include the functionality of the server-side validation function. If you create a client-side validation function without a corresponding server-side function, it is possible for malicious code to bypass validation.


Multiple validation controls can be associated with an individual input control to validate different criteria. For example, you can apply multiple validation controls on a TextBox control that allows the user to enter the quantity of items to add to a shopping cart. You can use a CustomValidator control to ensure that the value specified is less than the amount in inventory and a RequiredFieldValidator control to ensure that the user enters a value into the TextBox control.

Note:
If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.


It is possible to use a CustomValidator control without setting the ControlToValidate property. This is commonly done when you are validating multiple input controls or validating input controls that cannot be used with validation controls, such as the CheckBox control. In this case, the Value property of the arguments parameter passed to the event handler for the ServerValidate event and to the client-side validation function always contains an empty string (""). However, these validation functions are still called, where appropriate, to determine validity on both the server and the client. To access the value to validate, you must programmatically reference the input control you want to validate and then retrieve the value from the appropriate property. For example, to validate a CheckBox control on the server, do not set the ControlToValidate property of the validation control and use the following code for the handler for the ServerValidate event.


Client Side Validation
Controls..
  • Textbox
  • CustomValidator
  • ASP Button
  • Label 
Property..
   CustomValidator
  • ErrorMessage="Please provide value less than 50"
  • ClientValidationFunction="validateage"
  • ControlToValidate="TextBox1"
aspx code..
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 <asp:CustomValidator ID="CustomValidator1" runat="server"
            ErrorMessage="Please provide value less than 50"
            ClientValidationFunction="validateage" ControlToValidate="TextBox1"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
<asp:Label ID="Label1" runat="server"></asp:Label>

Client Function..
 
<script language="javascript">
        function validateage(source, arguments)
        {
            var ob=document.getElementById('TextBox1');
            if(arguments.Value<50)
                arguments.IsValid=true;
            else
                arguments.IsValid=false;

        }
    </script>
Server Side code.. 

protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Running Server code";
    }

Server Side Validation 

In server side validation all steps will be same as in client side 
the only change will be in custim validation property set it
 OnServerValidate="ServerValidation"

Server Side Code..

 protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Label1.Text = "Validated";
        }
        else
        {
            Label1.Text = "Page is not valid!";
        }

    }
    protected void ServerValidation(object source, ServerValidateEventArgs arguments)
    {

        int i = int.Parse(arguments.Value);
        arguments.IsValid = (i > 50) ? false  : true;

    }
 

ValidationSummary

Displays a list of all validation errors on the Web page.
The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property. The error message displayed in the ValidationSummary control for each validation control on the page is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed in the ValidationSummary control for that validation control. You can also specify a custom title in the heading section of the ValidationSummary control by setting the HeaderText property.
You can control whether the ValidationSummary control is displayed or hidden by setting the ShowSummary property. The summary can also be displayed in a message box by setting the ShowMessageBox property to true.
For more information on the ValidationSummary control, see the System.Web.UI.WebControls..::.ValidationSummary class.




















Controls..
  • 2 Textbox
  • 2 Requirefield validater
  • 1 Validate Summary
Proprty..
   RequiredFieldValidator 1
  •  ControlToValidate="TextBox1"
  • ErrorMessage="Please enter roll number." 
   RequiredFieldValidator 2
  •  ControlToValidate="TextBox1"
  • ErrorMessage="Please enter roll number."
aspx page code..
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox1" ErrorMessage="Please enter roll number.">*</asp:RequiredFieldValidator>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
            ControlToValidate="TextBox2" ErrorMessage="Please enter name">*</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
<asp:Label ID="Label1" runat="server"></asp:Label>
 
Server Side Code..
 
 protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text="page is valid";

    }