Is it possible to set the ValidationExpression
of a RegularExpressionValidator
using JavaScript? I'm using ASP.NET 3.5.
Here's why I want to do this...
On a payment page I have a DropDownList
that allows my user to select their card type. Beneath that is a TextBox
in which they type their card number.
I want to use a RegularExpressionValidator
to validate that their card number is valid for their given card type. The card payment processing is performed manually in a different system, so I cannot rely on this to catch incorrect card details.
Therefore I need to use a different ValidationExpression
for each card type. I would like to set the ValidationExpression
using JavaScript, firing off the DropDownList
onchange event.
My DropDownList
is bound to an XML document:
<asp:DropDownList ID="ddlCardType" runat="server"
DataTextField="Text" DataValueField="Value"
DataSourceID="xdsCardTypes" AppendDataBoundItems="True">
<asp:ListItem Text="(select)" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:XmlDataSource ID="xdsCardTypes" runat="server"
DataFile="~/App_Data/PaymentCards.xml">
</asp:XmlDataSource>
Here's the XML doc:
<?xml version="1.0" encoding="utf-8" ?>
<PaymentCards>
<PaymentCard Text="American Express" Value="AmericanExpress" RegEx="3[47](\d{13})" />
<PaymentCard Text="MasterCard" Value="MasterCard" RegEx="5[1-5](\d{14})" />
<PaymentCard Text="Maestro" Value="Maestro" RegEx="(5018|5020|5038|6304|6759|6761)\d{8,15}" />
<PaymentCard Text="Visa" Value="Visa" RegEx="4(\d{15}|\d{12})" />
</PaymentCards>
In code-behind I'm creating a JavaScript function call and adding it to the onchange event of the DropDownList
:
XDocument paymentCards = XDocument.Parse(xdsCardTypes.GetXmlDocument().InnerXml, LoadOptions.None);
List<string> regExes = paymentCards.Descendants("PaymentCard")
.Select(pc => pc.GetAttribute("RegEx").Value).ToList();
string setRegExValidatorScript = string.Format("setRegExValidator('{0}', '{1}', {2});",
ddlCardType.ClientID,
txtCardNumber_RegularExpressionValidator.ClientID,
regExes.ToJavaScriptArgumentList());
ddlCardType.AddAttribute("onchange", setRegExValidatorScript);
And in a referenced .js file I have the following:
function setRegExValidator(ddlCardTypeID, regExValidatorID, regExes)
{
var regEx = regExes[$get(ddlCardTypeID).selectedIndex];
var val = $get(regExValidatorID);
// TODO: Set the ValidationExpression!
}
So my one missing link is the ability to set the ValidationExpression
from JavaScript. Yes I could use a postback to achieve this, but that seems unnecessary.
(Suggestions on an alternate approach are also welcomed!)