Wednesday, September 06, 2006

asp:CustomValidator changing ErrorMessage displayed

requirement: custom validate the amount value; is required only if ddlContributionType value is 2 or 3.

code:
<!-- aspx -- >
<asp:dropdownlist id="ddlContributionType" runat="server">
<asp:textbox id="txtAmount" runat="server">
<asp:customvalidator id="CustomValidateAmount" runat="server" controltovalidate="txtAmount" errormessage="Invalid" clientvalidationfunction="CustomValidateAmount_ClientValidate" onservervalidate="CustomValidateAmount_ServerValidate" />

function CustomValidateAmount_ClientValidate(oSource,oArguments)
{
var ddlContributionType;
if (oSource.getAttribute("ContributionType") != null)
{
ddlContributionType = document.getElementById(oSource.getAttribute("ContributionType"));
}
if (ddlContributionType != null)
{
if ( (ddlContributionType.value != "2") && (ddlContributionType.value != "3") )
{
oArguments.IsValid = true;
return;
}
}
else
{
oArguments.IsValid = true;
return;
}
var amount = oArguments.Value;
oArguments.IsValid = false;
if ( isNaN(amount) == true)
{
oSource.innerHTML = "Invalid amount";
return;
}
var re = new RegExp("^\\d+(\\.\\d{1,2})?$");
m = amount.match(re);
if (m == null)
{
oSource.innerHTML = "Invalid amount format";
return;
}
if ( amount < innerhtml = "Minimum donation of $1 required"> 9999.99 )
{
oSource.innerHTML = "Maximum donation is $9999.99";
return;
}
oArguments.IsValid = true;
}

' .aspx.vb Page_Load
CustomValidateAmount.Attributes("ContributionType") = ddlContributionType.ClientID.ToString()

I explicity not included the check if required for condition 2 or 3, as i re-use an existing validator (RequiredFieldValidatorWithAEnablingCondition) that i developed long back, will mail the code if requested

<KCC:RequiredFieldValidatorWithAEnablingCondition runat="server" ID="RequiredFieldValidatorWithAEnablingConditionAmount" ControlToValidate="txtAmount"
ControlToCompare="ddlContributionType" TriggerValue="2;3" ErrorMessage="Required." />

No comments: