Validate a form before submitting it in ASP.NET

May 7, 2007

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.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (3) -

harsha
harsha United States
5/9/2007 9:25:37 PM #

Nice find..

Josh Stodola
Josh Stodola United States
6/4/2007 12:07:56 PM #

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?

Mads Kristensen
Mads Kristensen Denmark
6/4/2007 12:30:21 PM #

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.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.