13.07.2015 Views

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

ASP.NET 3.5: A Beginner's Guide - www.mustafaof.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

236<strong>ASP</strong>.<strong>NET</strong> <strong>3.5</strong>: A Beginner’s <strong>Guide</strong>CustomValidatorThe CustomValidator control covers virtually any kind of validation case you wish tomake. If none of the other validator controls validates what you need, you make your ownvalidation routine.Custom validation works something like the OnClick property in a Button control.The value assigned to OnClick is a C# event handler function. It can do whatever youput into the event handler function. The key property of the CustomValidator control isthe OnServerValidate event. Instead of having a built-in function to deal with thevalidation process, it passes a parameter to the C# event handler function and then codesthe out<strong>com</strong>e. For example, the <strong>ASP</strong>.<strong>NET</strong> codeOnServerValidate="MyValidation"calls the C# function MyValidation. That’s what the OnClick event does. However,you will find a key difference in the function’s parameter. Instead of EventArgs, thesecond parameter type is ServerValidateEventArgs. It even requires an additionalnamespace statement:using System.Web.UI.WebControls;Once that is set up, you still need some way of handling the event generated by clickingthe button. That’s easy enough. Just add a regular event handler function the same asalways. However, when both a validation event and a button event are in an <strong>ASP</strong>.<strong>NET</strong>script, the validation event is handled first. The following sequence shows what goes on:Click button > Sets off validation function > Sets off button functionThat sequence may seem counterintuitive. After all, the event handler called by the buttonis supposed to fire as soon as the user clicks the button. However, because the same<strong>ASP</strong>.<strong>NET</strong> listing has an event handler for a validation control, it launches the validationfunction instead.Keep in mind that most of the typical validation you will need can be ac<strong>com</strong>plishedusing one of the other validation controls, so it’s only when you cannot use one of themthat you will need a custom validator. This next example shows where you will needcustom validation. The routine is used to find directions to different cities. (You willhave to use your imagination that a database provides a wealth of detail and a number oflocations instead of just three cities and fairly terse directions.) If the city the user enters isnot in the “database,” it throws an error message. Otherwise, it provides directions.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!