38

I have following code with a RequiredFieldValidator. The EnableClientScript property is set as "false" in the validation control. Also I have disabled script in browser.

I am NOT using Page.IsValid in the code behind. Still, when I submit without any value in textbox I will get error message.

From comments of @Dai, I came to know that this can be an issue, if there is any code in Page_Load that is executed in a postback. There will be no validation errors thrown.

(However, for button click handler, there is no need to check Page.IsValid)

if (Page.IsPostBack)
{
    string value = txtEmpName.Text;
    txtEmpName.Text = value + "Appended";
}

QUESTION

  1. Why does not the server side validation happen before Page_Load?
  2. Why does it work fine when I use Page.IsValid?
  3. Can you provide any reference to an article that explains this? (Not something that says - always use Page.IsValid; but something that says what are the mandatory scenarios to use Page.IsValid

UPDATE 1

Refer ASP.NET Validators Common Misconception

Page.IsValid is accessible only after running Page.Validate() method which is invoked implicitly somewhere after Page_Load. In case you keep all of your logic in a Page_Load event handler (which is highly discouraged!), call the Page.Validate() before checking the Page.IsValid.

Note: It is advised not to keep all the logic in Page_Load. If something is to happen on button click event, move it to button click event handler. If something is to happen on drop-down event, move it to drop-down selected item change event handler.

UPDATE 2

It seems like, we need to add If(Page.IsValid) in button click also if we are using a Custom Validator with server side validation. Refer CustomValidator not working well.

Note: Client side validation question is present here: Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)

MARKUP

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
    alert('haiii');
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ValidationSummary runat="server" ID="vsumAll" DisplayMode="BulletList" CssClass="validationsummary" ValidationGroup="ButtonClick" />
    <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName"
        EnableClientScript="false" ErrorMessage="RequiredFieldValidator" Text="*" Display="Dynamic"
        ValidationGroup="ButtonClick"></asp:RequiredFieldValidator>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="ButtonClick" />
</div>
</form>
</body>
</html>

CODE BEHIND

protected void Button1_Click(object sender, EventArgs e)
{
    string value = txtEmpName.Text;
    SubmitEmployee(value);
}

References:

  1. Should I always call Page.IsValid?
  2. ASP.NET Validation Controls – Important Points, Tips and Tricks
  3. CustomValidator not working well
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 2
    http://stackoverflow.com/questions/1039465/should-i-always-call-page-isvalid – Massimiliano Peluso Dec 07 '12 at 11:49
  • @MassimilianoPeluso That question is similar but not addressing same issue. It says "calling Page.IsValid even when no validation controls are on the page ". But I have validation controls in my page – LCJ Dec 07 '12 at 11:53
  • 1
    You need to show us your codebehind logic. Depending on how you've written your code it may or may not be necessary to check `IsValid`. For example, if your logic is in a Button click handler that is only invoked if the page is valid, then the `IsValid` check is done behind-the-scenes, but if your logic is in `Page_Load` guarded by `if( IsPostback ); Validate(); if( IsValid )` then you really do need to check the property. – Dai Dec 07 '12 at 11:54
  • Can you comment on what I need to clarify to fully answer your question(s)? I thought the answer provided covered your questions, but maybe something requires clarification? – Jaime Torres Dec 16 '12 at 15:45
  • @JTorres Can you provide reference to an article that explains this? (Not something that says - always use Page.IsValid; but something that says what are the mandatory scenarios to use `Page.IsValid` – LCJ Dec 20 '12 at 04:35
  • 2
    There is no such thing as a mandatory scenario for when to use `Page.IsValid` -- your logic dictates that as I eluded to in my answer. The only mandatory order of operations is that `Page.Validate` must be called (either by you or as dictated by a control during postback) prior to interrogating `Page.IsValid`. You only need to check `Page.IsValid` if your logic requires the page to be valid in order to continue. That being said, you should NEVER rely on an event not firing if the is not valid, and never assume "if I get here, the page must be valid." – Jaime Torres Dec 20 '12 at 13:31

2 Answers2

38

Validation occurs after Page_Load, but before event handlers (See http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

If your button does not cause validation, you must manually fire Page.Validate.

You may not interrogate Page.IsValid until after (1) you have called Page.Validate or (2) a control that causes validation was the source of/included in a postback.

If you require validation to occur before event handlers fire, you may use:

if (Page.IsPostback) 
{
   Page.Validate( /*Control Validation Group Name Optional*/ );
   if (Page.IsValid)
   {
       //Do some cool stuff
   }
}

You may also want to consider redesigning so you aren't required to do so.

In an event handler that handles a control which causes validation, Page.IsValid is guaranteed to be available. In all other cases, it is generally safer to re-request validation. One model for handling submissions on a form that has validators:

void btnSubmit_Click(object sender, EventArgs e)
{
   this.UpdateGUIWithSubmitRequest();
   if (Page.IsValid)
   {
      this.ProcessSuccessfulSubmission();
   }
   else
   {
      this.ProcessInvalidSubmission();
   }
}

If you are using a CustomValidator that has a very expensive validation step, you may consider caching the result in the HttpResponse.Cache so you do not have to re-validate if multiple calls to Page.Validate occur.

void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
   CustomValidator self = (CustomValidator)source;
   string validatorResultKey = self.ClientID;
   bool? validatorResult = Context.Items[validatorResultKey] as bool?;
   if (validatorResult.HasValue)
   {
      args.IsValid = validatorResult.Value;
      return;
   }

   bool isValid = this.DoSomethingVeryTimeConsumingOrExpensive();
   Context.Items[validatorResultKey] = isValid;
   args.IsValid = isValid;
}

This, of course, depends 100% on your architecture and whether or not you are able to assume that a passed/failed validation during initial validation still passes/fails during subsequent validations of the same Page Life Cycle.

Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
  • Do you mean CausesValidation="false" when you say "If your button does not cause validation" ? – LCJ Dec 07 '12 at 13:12
  • 1
    Yes, but there is a caveat. If `CausesValidation` is `false` but `UseSubmitBehavior` is `true`, I'm fairly certain some validation still occurs. I cannot find any good reference on it right now, but I believe I have run into a situation such as this. Perhaps someone on SO can comment whether or not this is truly the case. – Jaime Torres Dec 07 '12 at 13:16
  • You only need to check `Page.IsValid` if you you only want to perform action on a valid page. There are very real use cases where you may want to do something 100% of the time on a click, and something else if all validators passed. I'll expand on my answer a little just for kicks. – Jaime Torres Dec 12 '12 at 14:34
  • Also, checking `Page.IsValid` is not limited only to CustomValidators. If the client has javascript disabled, client side validation will not occur and it will all occur during the postback. – Jaime Torres Dec 12 '12 at 14:40
  • 1
    If a client side user has javascript turned off, will `page.isvalid` work on the server regardless as well? – Micro Sep 09 '14 at 16:26
  • 1
    Yes, server side validity checks are done regardless of javascript. The javascript portion just reduces unnecessary postbacks. It's important to remember that you should almost never trust anything from the client as users can easily tamper with it. – Jaime Torres Sep 09 '14 at 17:46
1

Submit button should have same validation group as validator control has. For example

 <asp:Button Text=" Submit " runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" ValidationGroup="vgCustomerValidation" />
Syed Nasir Abbas
  • 1,722
  • 17
  • 11