Problem solve Get help with specific problems with your technologies, process and projects.

ASP.NET client side validation

ASP.NET Web Form controls and HTML Server Controls can execute client side script before posting the page back to server. This tip shows how.

ASP.NET Web form controls and HTML Server Control can be made to execute client side script before posting the page back to the server. Here the author has taken an example of a button that, when clicked, calls a function Validate(), which is on the client side first, and then submits the page.

ASP.NET Web form control

Let us start with a button which is an ASP.NET Web form control type:
i.e <asp:button id="acceptButton" runat="server" Text="Submit" </asp:button>

In the Page_Load Event of this page write the following statement:
acceptButton.Attributes.Add("onclick", "return Validate()")

Here Validate() is a simple function written in JavaScript or VBScript. In this function all client side validations can be done. And when all the validation checks are met, then the function merely returns true to post the page back to the server. Returning false from the Validate() function does not post the ASP.NET page.

HTML Server Control

These controls are similar to the HTML control, However they have an attribute runat = "server", which makes them server controls.

<INPUT id="acceptButton" onclick="return validate();" type="button" value="Submit" name="myButton" runat="server" onserverclick="myButton_ServerClick">

Here we see that this control has two attributes: onClick, which calls the client side function Validate, and onServerClick, which calls the server side function. Here again we have the same validation function, which returns a boolean. Returning true causes the page to be posted to the server and execute the myButton_ServerClick() on the server.


Dig Deeper on ASP.NET development best practices

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.