Wednesday, April 11, 2012

How to validate a page using Java script

Lets consider a following scenario:

There is a web page which has many input control, and validators (required field validator, custom validator, etc).

Now, there is a link button which already has some javascript written for its "onclientclick" event.
So, generally when this button is clicked:
a. First,it will execute java scripts written in onClientClick
b. page-level validations (i.e. required field validators, etc) will be performed
c. if page-level validations are passed, server-side validations will be performed
d. if server-side validations are passed, server-side Click event will be executed.

So, even if the inputs are invalid, it will always execute, onClientClick.

But there are certain cases when you need your main code of OnClientClick javascript to be executed only if the page is valid.
In such cases, you can add a code to validate page in your onClientClick method, and to allow execution of further code only if page is valid. For that, we can use "Page_ClientValidate" and "Page_IsValid".

Write following java script in "onclientclick" event of that link button in order to achieve this -


OnClientClick = "if(typeof(Page_ClientValidate) == 'function')
{ Page_ClientValidate(); if (Page_IsValid == true) { JavaScriptFunctionForTargettedAction(); } } return false;"/>


Here JavaScriptFunctionForTargettedAction() is the javascript code/ method you have originally intended to execute in onclientclick evnet

1 comment:

  1. Thank you. This was really helpful. I'm a new asp.net developer.

    ReplyDelete

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive