简体   繁体   中英

Do I have to call Validate() in a code-behind file?

I have the following event handler in my code-behind file that fires whenever an HTML form is submitted to the server:

public void Validate_Form(object sender, EventArgs e)
{
    // Check that the page is loaded due to a postback:
    if (IsPostBack)
    {
        // Check that the page passed validation:
        if (IsValid)
        {
           // perform some logic...
        }
     }
}

My question is do I need to explicitly call Validate() method right before my if (IsValid) directive? What would be the difference between the following:

if (IsValid)                      Validate();
{                                 if (IsValid)
    ...              vs.          {
}                                     ...
                                  }

And since I am not seeing any errors / warnings, does that mean that the two above are identical? Thanks!

They are not the same output.So explain this with an example. (You should turn off javascript for testing)

Suppose you have a page as follows:

<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox runat="server" ID="txtTest1"></asp:TextBox>
            <asp:RequiredFieldValidator ValidationGroup="ValidationGroup1" runat="server" ControlToValidate="txtTest1"></asp:RequiredFieldValidator>
            <asp:Button runat="server" ValidationGroup="ValidationGroup1"  ID="btnValidate1" Text="Validate1" OnClick="Validate_Form" />

            <asp:TextBox runat="server" ID="txtTest2"></asp:TextBox>
            <asp:RequiredFieldValidator ValidationGroup="ValidationGroup2"  runat="server" ControlToValidate="txtTest2"></asp:RequiredFieldValidator>
            <asp:Button runat="server" ValidationGroup="ValidationGroup2"  ID="btnValidate2"  Text="Validate2" OnClick="Validate_Form" />
        </div>
    </form>
</body>

If we use first method:

public void Validate_Form(object sender, EventArgs e)
    {
        // Check that the page is loaded due to a postback:
        if (IsPostBack)
        {
            // Check that the page passed validation:
            if (IsValid)
            {
                // perform some logic...
            }
        }
    }

Validation buttons work properly.

But if we use second method:

public void Validate_Form(object sender, EventArgs e)
    {
        Validate();
        // Check that the page is loaded due to a postback:
        if (IsPostBack)
        {
            // Check that the page passed validation:
            if (IsValid)
            {
                // perform some logic...
            }
        }
    }

Then if fill txtTest1 and click on btnValidate1 IsValid return false! because Validate() checks all of validations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM