Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...