How does Page.IsValid work?

Posted by Lijo on Stack Overflow See other posts from Stack Overflow or by Lijo
Published on 2012-12-07T11:46:22Z Indexed on 2012/12/13 5:04 UTC
Read the original article Hit count: 203

Filed under:

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 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 the server side validation does not happen before Page_Load?
  2. Why it works fine when I use Page.IsValid?

UPDATE

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

© Stack Overflow or respective owner

Related posts about ASP.NET