Click here to Skip to main content
16,012,316 members
Articles / Web Development / ASP.NET

Parital page validation using validation controls and JavaScript

Rate me:
Please Sign up or sign in to vote.
3.00/5 (5 votes)
12 Sep 2006CPOL4 min read 41.3K   89   16  
A logical portion of an ASP.NET page can be validated independently by overriding the behavoiur of validator controls. I am going to validate different parts of the page independently so our control or a particular portion of the page will validate itself without affecting anything else on the page.

Introduction

A common practice in web development is to divide up a page into logical portions like header, footer, left panel, right panel, and content area. In ASP.NET, you can divide up your whole page or a logical portion of the page into physical parts in the form of Web User Controls that perform specific tasks, like doing user authentication in one control or portion, and doing some sort of search in another. Of course, every portion is independent of each other and requires some sort of validation before being submitted to the server.

ASP.NET provides validation controls that perform a basic validation on a page. Whenever a control on the page causes post back and has its CauseValidation property set to true, ASP.NET will validate all validators of that page. We want to validate the different parts of the page independently so our control or that particular portion of page should validate itself without affecting anything else that might be on the page, and also the validator should not be validated against any other component or control that raises a postback on the server.

There are two possible solutions:

  1. Validating portions of a page at client side.
  2. Validating implicitly through validator controls at server side.

Client-side validation has its advantage that values will be validated before being submitted to the server, and also provides a quick response to the user, but has the disadvantage that the user can modify the page validation logic and is ready to submit invalid values to server that might result in a website crash. Server side validation requires a postback, but the validation logic is safe enough.

After reading this article, you will be able to:

  1. Do partial validation of the page using client side (JavaScript)
  2. Do partial validation of the page using server side (validator controls)
  3. Add client-side script for a server control
  4. Describe how the ASP.NET engine generates server control IDs
  5. Describe how the validation mechanism works
  6. Describe how to raise a postback from JavaScript
  7. Conditionally prevent a postback from client side
  8. Support browsers other than IE for validation

Client-side solution

The client side consists of adding a client-side validation script for our Web User Control, and the validation successes raise a postback for this control from the client-side, thereby not affecting other server validation controls. The following statement does the same for you.

How to add a client-side script for a server control

C#
serverConrol.Attributes.Add("onmousedown", "Validatethis, 
                            WCtrlLogin_txtLoginName)");

The Add method adds an attribute to this server control while generating HTML for this control. serverControl is the name of the control for which you are going to write client-side script. onmousedown is the client-side event name for which you write the script, and the second parameter for the Add method is the function name, optionally with a parameter that will execute on the particular event.

How ASP.NET generates an ID for a control on the Web User Control

The second parameter of the validation function is WCtrlLogin_txtLoginName, where the text before _WCtrlLogin is the name of the Web User Control, and that after _txtLoginName is the name of the child control, and this is the logic of the ASP.NET engine to create a unique ID for child controls of Web User Controls.

Now you are ready to write the script. You can optionally add a script to the page by writing Response.write(“All validation script”), or you can add the scripting logic in a separate file and link that file to your ASPX page. In my case, I have write it in a separate file and just check if the text box is empty. You can implement your complex validation here depending upon your requirements.

How to raise and prevent a postback from the client-side

Here is the function that checks for an empty value in a text box, and if something is found, calls its Click method causing the postback to occur, and if empty, alerts the user and postback of the control will be prevented by default

Note: The Click method is written on the server side:

JavaScript
function Validate(obj,obj1)
{
    if(obj1.value=="") 
    {
        alert("Please Enter Login Name");
        obj1.focus();
    }
    else
    {
        obj.click();
    }
}

Server side solution

To implement the server-side solution, you have to do the following steps: set the EnableClientScript property to false for every validator on your control. Add the following snip of code in the Load event of your control, which loops through each of the controls in your User Control.

C#
foreach (object item in Controls)
{
   if (item.GetType().IsSubclassOf(typeof(BaseValidator)))
        ((BaseValidator)item).Enabled=false;
}

And, it checks the control's type by checking if it's a subclass of BaseValidator. BaseValidator is the name of the base validator class from which all validator controls must derive. Set its Enabled property to false.

On the Button’s Click event, add the following snippet of code:

C#
private void btnSearch_Click(object sender, System.EventArgs e)
{
    bool bCheck=true;

    foreach (object ctrl in Controls)
    {
        if (ctrl.GetType().IsSubclassOf(typeof(BaseValidator)))
        {
            BaseValidator validator=(BaseValidator)ctrl;
            validator.Enabled=true;
            validator.Validate();

            if(!validator.IsValid) 
            {
                bCheck=validator.IsValid;
            }
        }
    }

    if(bCheck)
    {
        this.Label1.Text="doing search now";
    }
    else
    {
        this.Label1.Text="";
    }
}

Now, the postback will occur without validating any control, and on the server, we loop through the controls and find the validation controls. Here, we will first enable our validation controls and explicitly validate each control if validation is passed. We will write the code to do the actual search, and if that fails, validation messages will appear and nothing will happen.

Conclusion

You can implement partial page validation with a combination of client-side and server-side solutions for a rock-solid and efficient validation using validator controls.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Systems Limited
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --