asp.net custom validator not firing for textbox

42.4k Views Asked by At

I have both a required field validator and custom validator for validating a texbox. The required field validator fires perfectly. I'm not able to get the custom validator to fire properly?

<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />

<asp:RequiredFieldValidator display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />

 <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" />

code behind

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        Response.Write("firing - test");
        Response.End();


        if (e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }
8

There are 8 best solutions below

5
On

The problem is that you're calling Response.End() which effectively stops all execution of the page. Thus, the if/else block isn't being run at all. Comment that line out or skip over it while debugging and the validator will fire as expected.

I suggest you use a debugger instead of writing responses out in this fashion or be aware of the consequences of Response.End() if you choose to use it.

1
On

As far as I remember, custom validator will not fire if your textbox is empty.

6
On

Check that you have the your CustomValidator property ValidateEmptyText set to true so that empty text will be validated. Then you will not need the RequiredFieldValidator anymore.

EDIT: I took your code and copy and pasted it into an empty project and it works as expected. There must be something you have not posted, or is posting incorrectly, that we are not aware of. Is there anything else that affects the button that is triggering the validation or the validation controls themselves?

EDIT: Here is the exact code (it's in a content page):

aspx page:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />  
    <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" /> 
</asp:Content>

.cs page (empty Page_Load):

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{ 
    // put a break point here and it stops on it
    if (e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
} 
0
On

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!

0
On

Remember to set this property on the CustomValidator...

ValidateEmptyText="True"
0
On

if you have multiple part in your code and each part has some validator, create validateGroup for each part

0
On

In addition to the suggestions above, I've found that with newer versions of the .Net framework you must explicitly fire the validate() method at the server to get the custom validator routine

    // validate page before allowing import to go through
    Page.Validate();
    if (!Page.IsValid)
        return;
1
On

Ok... really old question with no accepted answer yet, and I just ran into the same issue.

So I'm going to throw this out there for anyone else who might have this problem and needs an answer...

If your're doing regular validations, along with custom server validations, the custom server validation will only fire if all other validations come back clean, at least, that's the way it's worked for me.