Sunday, April 5, 2009

Custom Validator

In the following example:
  • Required field validator for drop down list
  • Validate if any of the txtPostcode, txtSuburb, ddlCountry is filled in, then txtAddress is required.
  • ValidateEmptyText property is important for the validator to work

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="CustomValidator._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>Untitled Page</title>

<script language="javascript" type="text/javascript">

function cv_Validate(source, args)

{

var txtPostcode = document.getElementById("<%=txtPostcode.ClientID %>").value;

var txtSuburb = document.getElementById("<%=txtSuburb.ClientID %>").value;

var ddlCountry = document.getElementById("<%=ddlCountry.ClientID %>");

//alert(ddlCountry.selectedIndex);

if (txtPostcode.length > 0 txtSuburb.length > 0 ddlCountry.selectedIndex > 0)

{

If (args.Value.length <= 0)

{

args.IsValid = false;

}

else

{

args.IsValid = true;

}

}

else

{

args.IsValid = true;

}

}

function ValidateDropDown(source, arguments) {

var ddlCountry = document.getElementById("<%=ddlCountry.ClientID %>");

if (null != ddlCountry) {

var iValue = new Number(ddlCountry[ddlCountry.selectedIndex].value);

arguments.IsValid = (iValue > 0);

}

else {

arguments.IsValid = false;

}

}

</script>

</head>

<body>

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

<div>

<asp:TextBox ID="txtAddress" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator4" ControlToValidate="txtAddress" Text="Address Required!"

ClientValidationFunction="cv_Validate" runat="server" Display="Dynamic" ValidateEmptyText="true" />

<asp:TextBox ID="txtSuburb" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:TextBox ID="txtPostcode" runat="server" Width="290px" CssClass="clsNormal"></asp:TextBox>

<asp:DropDownList ID="ddlCountry" runat="server" CssClass="clsNormal">

<asp:ListItem Text="Select" Value="0"></asp:ListItem>

<asp:ListItem Text="Aus" Value="1"></asp:ListItem>

<asp:ListItem Text="NZ" Value="2"></asp:ListItem>

</asp:DropDownList>

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateDropDown"

ErrorMessage="*" ForeColor="Red" Display="Dynamic"></asp:CustomValidator>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</div>

</form>

</body>

</html>


Reference:

Custom Validator On DropdownList Control

blog comments powered by Disqus