我也有这个问题。是的,所有其他验证者都必须在火灾发生前通过。CustomValidator
但是,如果这对您不起作用,那么您可能需要使用Page.Validate()
.
我就是这样做的,我仍然设法保留我的RequiredFieldValidator
并且不需要ValidateEmptyText="true"
.
在文本框中添加一个陷阱以强制验证。
<asp:TextBox ID="txtLeft" runat="server" Width="110px" TextMode="SingleLine" style="text-align:center" OnTextChanged="TextBoxChanged_DateTimeTest" AutoPostBack="True" ValidationGroup="vg2"></asp:TextBox>
请注意,我使用的是特定的ValidationGroup
“vg2”,因为我还有其他不想验证的区域。
另外,我想验证日期和时间!
你还需要两件事。方法TextBoxChanged_DateTimeTest
...
protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
{
Page.Validate("vg2");
if (!Page.IsValid)
{
TextBox tb1 = (TextBox)sender;
IFormatProvider culture = new CultureInfo("en-AU", true);
//if page is not valid, then validate the date here and default it to today's date & time,
String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
DateTime dt1;
DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
if (dt1.ToShortDateString() != "1/01/0001")
tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
else
tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
}
}
而且您还需要服务器端验证CustomValidator
. 在我的情况下,文本框必须接受日期和时间!
所以这里是标记...
<asp:CustomValidator ID="CustomValidator3" runat="server" ControlToValidate="txtLeft" ErrorMessage="Invalid date & time format (dd/MM/yyyy HH:mm)"
SetFocusOnError="true" ValidationGroup="vg2" OnServerValidate="CustomValidator_DateTime"></asp:CustomValidator>
这是背后的代码......
protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
{
Page.Validate("vg2");
if (!Page.IsValid)
{
TextBox tb1 = (TextBox)sender;
IFormatProvider culture = new CultureInfo("en-AU", true);
//if page is not valid, then validate the date here and default it to today's date & time,
String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
DateTime dt1;
DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
if (dt1.ToShortDateString() != "1/01/0001")
tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
else
tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
}
}
祝你好运!