Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net - Setting RegularExpressionValidator ValidationExpression at runtime

I am setting a RegularExpressionValidator at runtime in my aspx control as per below

 <asp:RegularExpressionValidator ID="revValue" runat="server" ControlToValidate="txtZipCode"
                    ValidationExpression='<%=this.SettingManager.GetSettingValue("ZipCodeValidationExpression")%>'
                    ErrorMessage="Invalid Zip Code." Display="Dynamic" />

On the page, if I enter an invalid zipcode I do get the message "Invalid Zip Code", however, if I then enter a valid zip code nothing happens and the message remains "Invalid Zip Code".

If I manually set the expression as per below

 <asp:RegularExpressionValidator ID="revValue" runat="server" ControlToValidate="txtZipCode"
                    ValidationExpression="^(d{5}-d{4}|d{5}|d{9})$|^([a-zA-Z]d[a-zA-Z] d[a-zA-Z]d)$"
                    ErrorMessage="Invalid Zip Code." Display="Dynamic" />

It works fine. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sample code in "Code Behind"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Default3 : System.Web.UI.Page
{
    public static string GetErrorMessage()
    {
        return "Your Error Message";
    }

    public static string GetValidationExpression()
    {
        return @"d+";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            qw.ErrorMessage = GetErrorMessage();
            qw.ValidationExpression = GetValidationExpression();
        }
    }
}

Sample code in ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txt1" runat="server">
    </asp:TextBox>
    <asp:RegularExpressionValidator ID="qw" runat="server" ControlToValidate="txt1" Display="Dynamic"></asp:RegularExpressionValidator>
    <asp:Button ID="ed" runat="server" Text="ed" />
    </form>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...