Validate a form before submitting it in ASP.NET

by Mads Kristensen 8. May 2007 06:00

If you have added some ASP.NET validators to a webform, you might want to run them before hitting the submit button. In BlogEngine.NET we need to run the validators when a new comment is about to be added, but because it is using AJAX to post the comment we don’t submit the form.

The form is only used to take advantage of the validators and the server controls such as TextBox and they are still needed for clients that don’t support AJAX. What we needed was a way to validate the page from a custom JavaScript function.

Whenever a validator is added to a webform, a reference to the WebResource.axd JavaScript file is added as well. In here is all the mechanics used to do client-side validation and a lot of other useful things. It holds a function called Page_ClientValidate() which runs all the validators and returns true if all validators validates, otherwise it returns false. It also makes sure to show the error message of the validators that fail.

You can use it from within a button by specifying the onclick client-side event like so:

<input type="button" value="Save" onclick="if(Page_ClientValidate()){DoSomething()}" />  

If the Page_ClientValidate() function returns false, nothing happens and the error message of the individual validators that failed is shown. If it returns true, then everything validates and you can proceed. Just remember to do a manual server-side validation as well.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags: , ,

Client-side | ASP.NET

Comments

5/10/2007 6:25:37 AM #

harsha

Nice find..

harsha United States |

6/4/2007 9:07:56 PM #

Josh Stodola

Pressing the <enter> key to submit the form will not fire the button's onclick event, correct?  Perhaps using the onsubmit event of the form is a better alternative.  What are your thoughts on this, Mads?

Josh Stodola United States |

6/4/2007 9:30:21 PM #

Mads Kristensen

Josh, That's the hole point of validating before submitting. You don't do it on the submit button but in a javascript function somewhere. Otherwise you don't need to do it at all. Consider the scenario where you want to validate on the page load in javascript. Then you don't want to submit the content, just display the validation messages.

Mads Kristensen Denmark |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008