Search code examples
c#javascript.netvalidationcode-behind

How reliable is the ASP.NET Validator?


I decided to use the ASP.NET Validator to validate my dozens of inputs of my WebForm. It works fine on the Client side. I mean, i'm totally ok with validating the inputs without "Posting the Page back" etc.

But when i try to use the Validator on code behind, it gives me that Page.Isvalid attribute, and i get confused with its reliability. Here is the questions that i couldn't answer by myself:

  1. Is Validator reliable enough to be used on client side? (Besides disabling javascript, can it be manipulated?)
  2. How does this Validator reach the validity information on server side? (Is there a generated C# Validator code somewhere or does it take the info directly from the client-side?)

Here is the code that i wrote to validate my inputs also on server side:

foreach (IValidator iValidator in Page.Validators)
            {
                if (!iValidator.IsValid) { return false; }
            }

But, is it independent from .aspx and .js? Can i rely on it on server side?


Solution

  • You should always validate also on serverside, this is mostly done automatically by calling Page.Validate.

    From MSDN:

    This method is invoked when a user clicks any ASP.NET server control that has the CausesValidation property set to true, which is the default. These include the Button, ImageButton, and LinkButton Web server controls, the HtmlInputButton, HtmlInputImage, and HtmlButton HTML server controls, and controls that can automatically post back to the server such as the TextBox, CheckBox, ListControl, and BulletedList controls.

    If you want to force validation of a different ValidationGroup you can call it manually:

    Page.Validate("MyValidationGroup");
    If(Page.IsValid)
    {
        // ...
    }
    

    Note that you should check Page.IsValid only after you have called the Page.Validate method, or set the CausesValidation property to true in the OnServerClick event handler for an ASP.NET server control that initiated the form processing.