Wednesday 30 January 2008

Client-side validation controls

Client-side validation controls (e.g. RegularExpressionValidator) are really good for spotting incorrect input before any server-side processing takes place because the page is prevented from doing a postback.

What if you override the client click event (OnClientClick) of a button that is associated with one or more validation controls. Would you expect a similar behaviour? Wrong! The custom script is executed regardless of the validation.

The desired outcome of the following example is to get a popup when the button is clicked if the text box isn't empty:

<asp:TextBox ID="tbName" runat="server" ValidationGroup="Name" />
<asp:Button runat="server" Text="Submit" OnClientClick="javascript:alert( 'hello world' );" ValidationGroup="Name" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="tbName" Text="*" ValidationGroup="Name" />

The actual outcome is a popup even if the text box is empty. To make sure the page is valid, call Page_ClientValidate to update Page_IsValid (true/false) and add a condition around your script:

<asp:TextBox ID="tbName" runat="server" ValidationGroup="Name" />
<asp:Button runat="server" Text="Submit" OnClientClick="javascript:Page_ClientValidate(); if ( Page_IsValid ) { alert( 'hello world' ); }" ValidationGroup="Name" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="tbName" Text="*" ValidationGroup="Name" />

No comments: