Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts

August 25, 2011

RangeValidator is a validation control provided by asp.net. This control can be used to validate a range of string, date, integer and double values. In this post, I will show how to use the RangeValidator to validate a range of date using today’s date as the maximum value.

The following is the RangeValidator markup.

RangeValidator markup
  1. <asp:TextBox ID="T1" runat="server"></asp:TextBox>
  2. <asp:RangeValidator ID="RV1" runat="server" ControlToValidate="T1" Type="Date" MinimumValue="01/01/2000" ErrorMessage="*"></asp:RangeValidator>
  3. <asp:Button ID="Button1" runat="server" Text="Button" />

The TextBox control is added where the users will enter the value. The Button control is added to test validation. The RangeValidator is added – its ControlToValidate property is set to TextBox’s id, data type is set to Date, the minimum value is set to an arbitrary date. The maximum value is set in the Page_Load event as shown below.

Page_Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     RV1.MaximumValue = DateTime.Today.ToShortDateString();
  4. }

The maximum value expects a value of type string, so the string format of today’s date is passed as the MaximumValue.

November 20, 2010

The Validation Summary control in asp.net displays error messages when the button is clicked. The other validation controls, like Required Field Valuators or Compare Valuators controls displays error messages when the controls it’s validating loses focus or changes. There is no built in control that displays a summary of all validation errors in a separate controls.

In this blog post, I will create a asp.net page, add couple of controls – Textbox and DropDownList and add validation controls for these. I will also add custom javascript that checks the validation controls are displaying error messages and populates the custom validation control accordingly.

From the javascript, I have checked whether the validation controls are showing any messages and populated the validation summary section. Also, OnBlur event of Textbox and onchange event of Dropdownlist is used to check for the errors.

Code Snippet
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Validation.aspx.cs" Inherits="WebApplication1.Validation" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. <script type="text/javascript">
  4.     function ShowError() {
  5.         var msg = document.getElementById("spanError");
  6.         var reqV = document.getElementById('<%= RequiredFieldValidator1.ClientID %>');
  7.         var comV = document.getElementById('<%= CompareValidator1.ClientID %>');
  8.  
  9.         msg.innerHTML = "";
  10.  
  11.         if (reqV.style.visibility == "visible")
  12.             msg.innerHTML += "Textbox1 is required" + "<br/>";
  13.  
  14.         if (comV.style.visibility == "visible")
  15.             msg.innerHTML += "Drop down list is required";
  16.                          
  17.     }
  18.  
  19. </script>
  20. </asp:Content>
  21. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  22.  
  23.  
  24.     <asp:TextBox ID="TextBox1" runat="server" onblur="ShowError()"></asp:TextBox>
  25.     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  26.         ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
  27.     <br />
  28.     <asp:DropDownList ID="DropDownList1" runat="server" onchange="ShowError()">
  29.         <asp:ListItem>Select:</asp:ListItem>
  30.         <asp:ListItem>1</asp:ListItem>
  31.     </asp:DropDownList>
  32.     <asp:CompareValidator ID="CompareValidator1" runat="server"
  33.         ControlToValidate="DropDownList1" ErrorMessage="*"
  34.         Operator="NotEqual" ValueToCompare="Select:"></asp:CompareValidator>
  35.     <br />
  36.     <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ShowError()" />
  37.  
  38.     <div>Validation Summary:<br />
  39.     <span id="spanError"></span>
  40.     </div>
  41.  
  42. </asp:Content>

July 31, 2009

Check Date with CompareValidator

Asp.net provides validation controls to compare data between 2 controls or from a default value. The control responsible for this comparison is called CompareValidator and is represented as <asp:CompareValidator /> element.

The important attributes of this control are:
  • ErrorMessage: to display a custom error message.
  • ControlToCompare: ID of the control to compare against.
  • ControlToValidate: ID of the control that needs to be validated.
  • Operator: type of comparison (GreaterThan, Equal, NotEqual, LessThan, DataTypeCheck, GreaterThanEqual, LessThanEqual are valid values).
  • Type: type of value to compare against (Integar, Double, String, Date, Currency are valid values).
  • ValueToCompare: default value to compare.

The DataTypeCheck operator checks for the type of the data.

In the following example, I will show how to add a CompareValidator control apply it to a TextBox and set the ValueToCompare from code-behind to check if the TextBox contains a date that is greater than today's date.

The main page is below:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CompareValidator"
Operator="GreaterThan" Type="Date"></asp:CompareValidator>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>


The code behind is below.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.Date.ToShortDateString());
CompareValidator1.ValueToCompare = DateTime.Now.Date.ToShortDateString();
}



In the code behind, I am setting the ValueToCompare property to current date. Note that, the type of data to compare against is Date and not DateTime - therefore, I am using the ToShortDateString() method to get the date.

July 14, 2009

Custom validation from server side

On the previous article, I showed how to validate a control using CustomValidator and javascript. In this article, I will show how to validate a control from server side.

At first, we create a normal page, add a TextBox control, a CustomValidator and a Button control to perform postback. Here, is the code of the page.

<div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="TextBox2 not valid" ControlToValidate="TextBox2" OnServerValidate="CheckTextBox2" Display="Static"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Click" />
    </div>

The CustomValidator looks like other validation controls except it has a OnServerValidate property set to "CheckTextBox2" which is the method name that performs the validation.

The method simply checks if the text passed in TextBox2 has character length between 6 and 10. If not, it sets the IsValid property to false. Here is the code for the method.

   protected void CheckTextBox2(object source, ServerValidateEventArgs args)
        {
            string data = args.Value;
            args.IsValid = false;

            if (data.Length >= 6 && data.Length <= 10)
            { args.IsValid = true; }       
        }


The method must have the signature void MethodName(object source, ServerValidateEventArgs args). In the method, the TextBox2's Text property is retrieved using the args.Value property. The method starts by setting the IsValid to false and reset it to true if the logic succeeds.

When the page is run, and the Button is clicked - a postback occurs and the method CheckTextBox2 is called. If the IsValid property is false, that is validation fails, and ErrorMessage is displayed on the page.

At times, the built in validation controls are not sufficient to perform a validation for a particular business rules. In this situation, we can use the CustomValidator control and use either or both javascript and server side validation. Here, I will show how to use javascript to perform client-side validation using the CustomValidator control.

At first, I will create a normal page and then add a TextBox control whose content will be validated, a Button control that will simply perform a postback and a CustomValidator control to validate the TextBox. Here is the code for the page,

  <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CV1" runat="server" ControlToValidate="TextBox1" ErrorMessage="invalid" Display="Static" ClientValidationFunction="CheckTextBox"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Click" />
    </div>


The CustomValidator control looks similar to other validation control. It has an extra attribute ClientValidationFunction that is set to the javascript function name "CheckTextBox".

The javascript function checks for the length of the string data that is passed from the TextBox1 control. If it is not between 6 and 10 characters, then it returns an error. Here is the javascript function.

function CheckTextBox(source, arguments)
    {
        var data = arguments.Value.split('');
        arguments.IsValid = false;//set IsValid property to false

        if (data.length >= 6 && data.length <= 10) //check if the content is between 6 and 10 characters
        {
            arguments.IsValid = true;
        }
    }


The function must have the signature FunctionName(source, arguments). The arguments parameter has a property called "IsValid" that determines whether the page is valid or not. In the function, we start by setting the IsValid property to false. If the logic succeeds, we set the IsValid property to true.

When the page is run and we enter text in the TextBox1 control and click the Button - the javascript code is called and if the logic succeeds - the page postbacks successfully. Otherwise, the ErrorMessage is displayed and the page does not postback.

June 25, 2009

The validation controls in asp.net is capable of displaying an error message but it does not display success message. In this example, I will create a TextBox control, add a RequiredFieldValidator and then a custom javascript function to display a success message.

Here is the code for the page.

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <span id="successSpan" style="color:Red;"></span>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 is required" ControlToValidate="TextBox1"></asp:RequiredFieldValidator><br />       
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>


In the code for the page, there is a TextBox control, Button control, RequiredFieldValidator to validate the TextBox and a html span element that will contain the text for the success message.

In the Page_Load method for the page, I am adding an "onblur" attribute to the TextBox control.

protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Attributes.Add("onblur", "showSuccess()");
        }

This attribute will fire the showSuccess() function when the TextBox control loses focus. Here is the javascript code,

<script type="text/javascript">
        function showSuccess() {
            if (document.getElementById("<%= TextBox1.ClientID %>").value == "") {
                document.getElementById("successSpan").innerHTML = "";
                }
            else{
                document.getElementById("successSpan").innerHTML = "Success";
            }
        }      
</script>


The function checks if the TextBox control has any text or not. If not, it resets the span element's text or otherwise displays the text, "Success", in the span element.

Reference: Shahed Kazi at AspNetify.com