在验证摘要中显示动态添加的验证程序的错误消息
本文关键字:验证 程序 消息 添加 错误 显示 动态 | 更新日期: 2023-09-27 18:36:11
我按如下方式扩展了文本框类以充当DateTextBox并验证字段格式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Myapplication.App_Code
{
public class DateTextBox : TextBox
{
private RegularExpressionValidator regexval;
public string InvalidDate="Incorrect date format, must be dd/mm/yyyy";
public string ClientScript = "true";
protected override void OnInit(EventArgs e)
{
regexval = new RegularExpressionValidator();
regexval.ControlToValidate = this.ID;
regexval.ErrorMessage ="'"+this.Text+"'"+ this.InvalidDate;
regexval.EnableClientScript = (this.ClientScript.ToLower() != "false");
regexval.ValidationExpression = "^(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[-/.](19|20)''d''d$";
//regexval.Text = "*Incorrect date format";
regexval.ForeColor = System.Drawing.Color.Red;
regexval.Display = ValidatorDisplay.None;
Controls.Add(regexval);
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
Attributes.Add("placeholder", "dd/mm/yyyy");
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
regexval.RenderControl(writer);
}
}
}
在我的aspx中,我有这个日期文本框以及其他几个控件,这些控件具有现成的必需字段验证器。
这是我的aspx:
<td>
<RE:LabelExtended runat="server" ID="lblDateOfBirth" Text="Birth Date" Required="True">
</RE:LabelExtended>
<asp:RequiredFieldValidator ID="ReqValDateOfBirth" runat="server" ControlToValidate="txtDateOfBirth" ErrorMessage="Please enter Date of Birth" ForeColor="Red" Display="None" ></asp:RequiredFieldValidator>
</td>
<td>
<RE:DateTextBox runat="server" ID="txtDateOfBirth" Text='<%# Bind("DateOfBirth","{0:dd/MM/yyyy}") %>'></RE:DateTextBox>
</td>
<td>
<asp:ValidationSummary ID="Tab1ValidationSummary" runat="server" ShowSummary="true" ForeColor="Red" Enabled="true" />
</td>
我的问题是我的 DateTextBox 控件中的正则表达式验证器没有在验证摘要中与其他控件一起显示其错误消息。知道怎么做吗?
编辑:
我尝试为页面上的所有控件提供一个验证组,并为控件中的正则表达式提供相同的组,这使错误消息显示为必需,但我无法修复控件中的验证组,因为我有几个页面使用此控件。
在这里找到答案:
我向控件添加了Page.Validators.Add(regexval);
,它在没有验证组的情况下运行良好