mikebai.com

  • Home
  • dev
  • DotNET
  • M365
  • 搞笑
  • 杂七杂八
  • FocusDict
個人BLOG
it developer
  1. Main page
  2. DotNET
  3. Main content

Calling ASP.Net validators from JavaScript

2010-03-12 94hotness 0likes 0comments

There are situations when we want to call Asp.net validatiors form JavaScript. One 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. The following code shows a portion of asp.net page which includes one standard .net required field validator and one regular expression validator.


<table>


<tr>


<td><asp:Label ID=”lbl1″ runat=”server” Text=”Please enter a digit”></asp:Label></td>


<td><asp:TextBox ID=”txtbox1″ runat=”server”></asp:TextBox></td>


<td><asp:RequiredFieldValidator ID=”valReq” ControlToValidate=”txtbox1″ runat=”server” ErrorMessage=”*” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”valreg” ControlToValidate=”txtbox1″ runat=”server” ErrorMessage=”Not valid character” ValidationExpression=”[0-9]“>
</asp:RegularExpressionValidator></td>


</tr>


<tr>


<td></td>
<td><asp:Button ID=”btn1″ runat=”server” Text=”Submit” OnClientClick=”performCheck()”/></td> <td></td>


</tr>


</table>


In design mode, it looks as below


View in design mode

View in design mode


Now we want to make sure that .net validators get fired up on “Submit” button click before closing the window using javascript window.close(). In our example, we have a text box where we expect a single digit before closing the window.


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 closeing window.


<script type=”text/javascript” language=”javascript”>


function performCheck()
{


if(Page_ClientValidate())
{


window.close();


}


}
</script>


Now, if the Submit button is clicked leaving the text box empty, the required field validator will fire up as shown in the below screen shot.


Required field validotor fires up

Required field validotor fires up


If any thing is written in other than a single digit, we will get the following output.


Regular Expression Validator fires up

Regular Expression Validator fires up

Tag: Nothing
Last updated:2010-03-12

mikebai

This person is a lazy dog and has left nothing

Like
< Last article
Next article >

COPYRIGHT © 2025 mikebai.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang