30

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;
    }
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
Eric Savard
  • 301
  • 1
  • 3
  • 3
  • I always have problems with serverside validators, I always end up going with client side :( – jonezy Feb 25 '11 at 16:40
  • 1
    i'd also love to know the answer to this. – jonezy Feb 25 '11 at 16:40
  • Is the method firing at all? Have you set it as the validator's OnServerValidate event? Can you show us the ASPX tag for the validator? – Justin Morgan - On strike Feb 25 '11 at 16:44
  • Nope not firing at all, the tags are there? – Eric Savard Feb 25 '11 at 16:45
  • 5
    @jonezy: Be careful with client-side validators - they are easy to trick and submit malicious data. Always make sure you validate input on the server, one way or the other. – Andrey Feb 25 '11 at 17:01
  • This is a tricky one. Just for testing purposes, put a `Page.Validate()` and/or a `cusCustom.Validate()` in the Page_Load or some other place where you know it will be hit. Then step through and watch it hit. I have a feeling the event isn't registered, although it does look like it is from your code. BTW, what version of ASP.NET is this? – Justin Morgan - On strike Feb 25 '11 at 17:49
  • @Eric: my comment was in response to @jonezy – Andrey Feb 25 '11 at 22:29

8 Answers8

53

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;
} 
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • really eh, so something in my code is interfering with the firing of the event.. i have a bunch of required field validators for other text boxes and that's all. They all fire properly?? – Eric Savard Feb 25 '11 at 17:24
  • 1
    @Eric Savard You can do a simple test and just copy and paste the code you posted into an empty project. It works fine. You need to isolate what is causing it so I would start by commenting out as much code as possible and get it to work and then add it back slowly to figure out which snippet is causing the problems. – Kelsey Feb 25 '11 at 18:04
  • Kesley, can you please send me the code.. because i did exactly what you did with a new web form and it still doesn't work – Eric Savard Feb 25 '11 at 18:24
  • @EricSavard - Maybe I am commenting too late. But you need FieldRequired="True" to be set up sometimes it acts weird. – Akshay Anand Aug 10 '17 at 17:01
  • wow just wow... thanks man you saved the day... damn you Microsoft and your validators... – Edgar J. Rodriguez May 19 '19 at 00:40
19

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.

RoastBeast
  • 1,059
  • 2
  • 22
  • 38
Patrick
  • 7,512
  • 7
  • 39
  • 50
9

Remember to set this property on the CustomValidator...

ValidateEmptyText="True"
Remotec
  • 10,304
  • 25
  • 105
  • 147
5

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;
TedC
  • 51
  • 1
  • 3
4

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!

Fandango68
  • 4,461
  • 4
  • 39
  • 74
1

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.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
1

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

Andrey
  • 20,487
  • 26
  • 108
  • 176
  • 6
    a `CustomValidator` can fire on empty text if the `ValidateEmptyText` property is set to `true` as I have stated in my answer. This should remove his requirement for a `RequiredFieldValidator` as well. – Kelsey Feb 25 '11 at 17:06
0

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