0

Here's the deal: I built a custom validator that should only fire if there is input in the text box. When it fires, it should test to see if the text in the box is an integer, and it will reject it if not. It won't fire, though, and I'm trying to figure out why.

I put this void in the body of the partial c# class:

    protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
    {
        int num;
        bool isNum = int.TryParse(arg.ToString(), out num);

        if(arg.Value.Length>0){
            if (isNum)
             {
                arg.IsValid = true;
             }
             else
             {
                arg.IsValid = false;
             }
        }
        else{
            arg.IsValid=true;
        }
    }

The code for the validator is as follows:

 <div class="adult">
            <label>Adults ($10)</label>
            <asp:TextBox runat="server" ID="wAdultLunch" class="adultLunch" MaxLength="2" />
            <asp:CustomValidator ID="intValidate" ControlToValidate="wAdultLunch" ErrorMessage="Invalid number" OnServerValidate="intValidate_Validate" Display="Static" runat="server" EnableClientScript="False" ValidateEmptyText="True"></asp:CustomValidator>
 </div>

Insight would be appreciated!

EDIT: I attached the postback code below

<asp:Button ID="wSubmit" runat="server" Text="Submit" OnClientClick="return validateForm();" causesvalidation="true"/>
6
  • Could you include markup for the object causing the postback? Are you using CausesValidation='false' on that object? Also, do you check for IsValid inside your postback handler before proceeding? Commented Jul 31, 2012 at 21:45
  • I added the postback code for the button. How would I check for IsValid inside the postback handler, I feel like I haven't done that. Commented Aug 1, 2012 at 13:04
  • Although it doesn't answer your question directly, have you considered using <asp:CompareValidator Operator="DataTypeCheck" Type="Integer" ...> and <asp:RangeValidator ...>? Commented Aug 1, 2012 at 13:10
  • Can you confirm whether "does not fire" means that the function is not called (i.e. you put a break-point into the function, and it is never hit)... or do you mean that the ErrorMessage is never displayed? Commented Aug 1, 2012 at 13:13
  • Do you have any client-side validators? If they object to the input, the submit is cancelled and the server-side validators never run. Commented Aug 1, 2012 at 13:31

4 Answers 4

2

You are doing the parse on the wrong thing. arg.ToString() will give you the string of "System.Web.UI.WebControls.ServerValidateEventArgs", when you actually want to the arg.Value (which is already a string)

So, instead of...

bool isNum = int.TryParse(arg.ToString(), out num);

Change it to (note the .Value)...

bool isNum = int.TryParse(arg.Value, out num);

Although it is a lot more complex than it actually needs to be. The whole thing could be rewritten a lot more comprehensively like this...

protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
{
    int num;
    arg.IsValid = int.TryParse(are.Value, out num);
}

This is because TryParse will return a true if the conversion was successful, and false otherwise.

And as a final thought, all this could be achieved using the <asp:RequiredFieldValidator ...>, <asp:CompareValidator Operator="DataTypeCheck" Type="Integer" ...> and <asp:RangeValidator ...> validator controls.


UPDATE

As the OP points out, he doesn't want the error when when the textbox is empty, so instead try this...

protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
{
    if (args.Value.Length > 0)
    {
        int num;
        arg.IsValid = int.TryParse(are.Value, out num);
    }
    else
    {
        arg.IsValid = true;
    }
}

And has already been pointed out by @HansKesting... this will only ever be called if all client-side validation is passed. As soon as client-side validation fails, the submission of the form back to the server is also cancelled.

Sign up to request clarification or add additional context in comments.

7 Comments

That's helpful. Part of the reason that I was trying to get the argument length is that I want it to be valid if there is no value passed in, but if there is an argument then it needs to be a number.
Ah, ok @ijb109 - that makes sense... in that case put the parse within the if (args.Value.Length > 0) no point doing it on an empty string
Just to be certain, this will only activate when the submit button is clicked, correct? In this case, then, the client-side validation would keep it from validating, so to test it I would have to take that off.
@ijb109, not exactly. Client validation is designed to check for things on the client before the page is actually submitted back to the server - this is designed to reduce the load on the server. Only if ALL client-side validation has been passed will the form then be submitted back to the server - it is at THIS point that the ALL validation will be done again (to stop anybody trying to get around the client validation) including the code-behind custom validator code will fire, not before hand. Does that make a bit more sense to you?
That makes sense. If I used the CompareValidator like you had suggested before, would I be able to make it only validate if there is a value in the field?
|
2

I don't know if it's related, but I had an issue with a custom validator not firing. I had it validating a dropdownlist, which had a default value of an empty string. I had to set

ValidateEmptyString="true" 

and then it started working just fine.

You could also call the Validate() function and read the IsValid property from the custom validator control. However, the Page's validation function should work just fine, and shouldn't require such a call.

Comments

0

I suppose you have a server side event to execute if the validation passes. for ex: a button click event. In that if you check Page.IsValid then it will be false if the validation passes then Page.IsValid will be true. You need to use Page.IsValid to check whether the validation passed or not.

Comments

0

On the front-end try setting the CausesValidation attribute to true as shown below. See if that helps.

<asp:Button ID="btnSubmit" Text="Submit" CausesValidation="true" runat="server" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.