I want to use the asp:RegularExpressionValidator control to validate a number of text boxes. Some of the textboxes contain email addresses. I don’t want to repeat the same regular expression in the attributes of the RegularExpressionValidator for each different text box. Therefore I define the expression as a constant in my code-behind
Const regEmail As String = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
Similarly, I define the error message this way.
const regEmailMsg = "Email address does not appear to be valid."
However, I cannot find a way to include these strings in the RegularExpressionValidator controls in my ASPX page that works. Valid expressions are flagged as invalid. As an additional failure, the ValidatorCalloutExtender appears but its middle section is missing – the error message does not appear. Here is an example textbox and validator:
<asp:TextBox ID="txtIndividualEmail" runat="server" Width = "200"></asp:TextBox>
<asp:RegularExpressionValidator ID="revIndividualEmail" runat="server" ErrorMessage="<% =regEmailMsg %>" Display="None"
ControlToValidate="txtIndividualEmail" ValidationExpression="<% =regEmail %>" > </asp:RegularExpressionValidator>
<cc1:ValidatorCalloutExtender ID="vceIndividualEmail" runat="server"
Enabled="True" TargetControlID="revIndividualEmail" HighlightCssClass="validatorCalloutHighlight">
</cc1:ValidatorCalloutExtender>
When I include the strings directly in the ASPX everything works fine:
<asp:RegularExpressionValidator ID="revIndividualEmail" runat="server" ErrorMessage="Email address does not appear to be valid." Display="None"
ControlToValidate="txtIndividualEmail" ValidationExpression="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
Email is just one example of where I want to re-use a string for validation, and therefore don’t want to be repeating it in my ASPX. Is there a way to do this?
The only thing you can really do here is to set the properties in the code-behind in an
OnInitorOnLoadevent. Something like: