I had this problem too. Yes all other validators have to pass before the CustomValidator
fires.
However, if that does not work for you, then you may need to force a validate of your specific validation group using the Page.Validate()
.
This is how I did it, and I still managed to keep my RequiredFieldValidator
and no need for ValidateEmptyText="true"
.
Add a trap in the textbox to force a validate.
<asp:TextBox ID="txtLeft" runat="server" Width="110px" TextMode="SingleLine" style="text-align:center" OnTextChanged="TextBoxChanged_DateTimeTest" AutoPostBack="True" ValidationGroup="vg2"></asp:TextBox>
Note that I am using a specific ValidationGroup
"vg2", as I have other areas that I don't want to validate.
Also, I want to validate date & time!
You need two more things. The TextBoxChanged_DateTimeTest
method ...
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();
}
}
And you also need the server side validate for the CustomValidator
. In my case the TextBox has to accept a date & time!
So here's the markup...
<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>
And here's the code behind ...
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();
}
}
Good luck!