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.

If you have a broken internal link on your ASP.NET website and follow it, you will see the well known yellow screen of death (YSOD). Not only is it ugly, but it could also tell the visitor more than they should know about your system. The broken link sends a 404 HTTP status code to the client, but instead of providing the visitor with the YSOD, it will be better to use the browsers build-in view for those kinds of errors. It’s a view visitors know and not an arbitrary YSOD with strange information.

Of course, this is only true if you have no custom error HTML page. Keep in mind that custom error aspx pages are not good enough, because if a global ASP.NET exception occurs, then they won’t work either.

You can bypass the default YSOD by adding this method to the global.asax.

private void Application_Error(object sender, EventArgs e)
{
 HttpException ex = Server.GetLastError() as HttpException;
 if (ex !=null)
 {
  // When a HttpException occurs.
  Response.StatusCode = ex.GetHttpCode();
 }
 else
 {
  // When any other exception occurs.
  Response.StatusCode = 500;
 }

 Response.End();
}

The mothod removes the YSOD and let’s the browser decide what to display to the visitor.