Friday, September 3, 2010

Calling ASP.NET Validators form JavaScript

There are situations when we want to call Asp.net validatiors form JavaScript.
As I ran in to one of them as I was using “ICallbackEventHandler” in my page and dynamically creating matrix of text boxes, but as we know in callbacks, page is not posted back to server and in this situation validators not work at all. After lots of googling I found a mechanism of initiating validators to work at client end.
One more such situation is when we want to close a pop up window on button click using window.close(). But before closing the window using JavaScript, we want to validate the data written in the controls of the window.    
It possible to call Asp.net validators from JavaScript.
You may have validators like below on your page


<asp:TableCell>
    <asp:RequiredFieldValidator runat="server" ID="rfvWeight" ControlToValidate="txtWeight1"
    ErrorMessage="Please enter weight." ToolTip="Weight can't be empty."                      Display="Dynamic">*</asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="vldWeight"   ControlToValidate="txtWeight1" ErrorMessage="Please enter valid weight value" ToolTip="Please enter valid weight value" ValidationExpression="^[0-9]*\.?[0-9]+$"
    runat="server" Display="Dynamic">*</asp:RegularExpressionValidator>
    <asp:TextBox ID="txtWeight1" Width="50px" runat="server"></asp:TextBox>
</asp:TableCell>


Now we want to make sure that .net validators get fired up on “Submit” button click
All we have to do to fire up .net validators is to call “Page_ClientValidate()” function.  The following JavaScript code shows how “Page_ClientValidate()” function can be used before closing/Submitting  window.

function CallSrv() {
      if (Page_ClientValidate()) {
        //To Do
        }
}
If your page have more then 1 validation group then pass that group name to “Page_ClientValidate()”

No comments:

Post a Comment