ASP.Net正则表达式验证器动态设置ValidationExpression

时间:2012-09-14 20:15:16

标签: asp.net validation

我正在尝试这样做:

<obout:OboutTextBox ID="txtDistributorEmail" runat="server" Width="250" />
    <asp:RegularExpressionValidator ID="revDistributorEmail" runat="server"     
    ErrorMessage="An invalid email address was entered."                                 
    ValidationExpression='<%=Mynamespace.RegEx.EMAIL %>' 
    ControlToValidate="txtDistributorEmail" />

namespace Mynamespace
{
    public class RegEx
    {
        public const string EMAIL = @"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z] 
        [-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
    }
 }

即使输入了正确的电子邮件,验证也会失败。但是如果我用正则表达式ValidationExpression替换[],它就可以正常工作。

有什么不正确吗?

2 个答案:

答案 0 :(得分:0)

这是aspx页面的基础:

<%@ Import Namespace="Mynamespace" %>  

<asp:RegularExpressionValidator ID="revDistributorEmail" runat="server"     
    ErrorMessage="An invalid email address was entered."                                 
    ValidationExpression="<%# Mynamespace.RegEx.EMAIL %>" 
    Display="Dynamic"
    ControlToValidate="txtDistributorEmail" />

答案 1 :(得分:0)

试试这个;用于动态re验证。

RegularExpressionValidator re = new RegularExpressionValidator();
re.ControlToValidate = "textbox121"; //mention your textbox id
re.Style.Add("color", "Red");
re.ID = "Reg1";
re.ValidationExpression = "^[a-zA-Z\\s]+$";
re.ErrorMessage = "Special Characters Are Not Allowed";