|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionIt makes no difference what kind of development you are working on, user input validation is always an important and often troublesome issue. What data needs to be validated? What are the valid conditions? Do we need to report every error in one pass or allow the user to correct one error at a time? Do we validate on the client or on the server? The questions go on. Worse than that, the code can quickly get unmanageable, especially where we try to validate everything in one pass. Nested ifs, deconstructing strings, building up lists of error messages, endless comments trying to make some sense of it. It is my personal opinion that everything that can be updated by anyone else but me should be validated at every opportunity and that we should always validate everything in one pass. But that does not mean that I have never tried to dodge the bullet on a tight deadline. In some respects, it can be worse for the web page developer. It is important to validate as much as possible at the client to save on bandwidth, but HTTP requests are so easy to fake; the same data needs to be validated again on the server, if you want any kind of security. Another problem can arise if the customer wants you to mark the invalid fields and then list the errors in one place (a common user-friendly convention in web-page design). It is hard to imagine someone who enjoys writing validation code, and that goes double for classic ASP developers. Thankfully, the .NET framework has gone a long way to alleviate the problem for the ASP.NET developer with the introduction of six all-encompassing and developer-friendly validation controls:
This article assumes a basic knowledge of adding controls to a web form and setting the properties and event handlers. It attempts to give a general overview of these controls and how to use them to perform simple practical tasks. All examples use C# with BaseValidator controlsAll of the above, with the single exception of The first four validation controls are tailored for specific purposes and designed to validate an identical condition on both the client and the server. Each generates some purpose-specific JavaScript (using WebUIValidation.js, in the aspnet_client web) to validate the input control that you point to against the condition that the given validation control is designed to handle. The The actual client-side validation takes place in events triggered by a change of value in the control you are validating and when you try to submit the form. The server-side validation takes place when you post back the form and the validation results can be accessed using the Each control's properties look reasonably similar. Apart from the standard font and formatting properties, each of the standard controls has the following common properties, derived from
ControlToValidateA Of the standard controls, the only ones marked with a
It is worth bearing this in mind if you are ever developing a control that may require validation. You should always prefix the class definition with ErrorMessageThis defines the message related to the invalid condition. This can be displayed in the control itself or passed to a TextThe text to be displayed in the control when the condition is not valid. If left blank, the control will display the If the difference between EnableClientScriptBy default this is set to If the IsValidThe only property not available to the WebForm designer, This can be useful if you want to react differently when only part of the page is invalid. Examples
The following sections will refer to a very simple example. As shown in the screenshot, this example will consist of a single Create a web form, containing only a The Include some code in a private void myButton_Click(object sender, System.EventArgs e)
{
if (this.IsValid)
Response.Redirect("anvokay.aspx", true);
}
Or... if you are feeling lazy, you can download the sample code at the top of the page and unzip it into a new or existing web. NOTE: There is a strange behavior quirk in the interaction between web browsers and the .NET framework which means that if you hit Enter in a Single- This is apparently a legacy browser issue where, for a single textbox form, the button name is not sent as part of the response, leaving .NET with no idea what triggered the postback. Possible workarounds are:
(Thanks to Andy Smith for helping me understand this) The RequiredFieldValidatorAs the name suggests, the There is only one property unique to the
ExampleValidate our simple form, using a If you set And there you have it. You have now successfully implemented ASP.NET validation with one control and one line of code ( InitialValueThe Try changing both the You should find that if you do not change this text and simply hit "Submit", you will get the error message as specified, but now if you blank the field then it is considered valid. In many ways, this is a functionality overlap with the BaseCompareValidator controlsThe The
This one property, however, is very important and includes several "gotchas" that you might need to be aware of. TypeThe e.g.. If compared directly as strings, "90" is greater than "100"; but if compared as numbers, "90" is clearly less than "100". But be aware that both the Client and the Server validation will deal with the input data using the locale of the Server machine, unless you set the page or application
If you do not set the The 10th of January is before the 1st of October, after all, whichever country you come from. It is always worth noting on your page which format the user is expected to use (remembering that YYYY/MM/DD is considered culture-independent), but the more idiot-proof you make things, the bigger idiot the internet produces. You cannot guarantee that the user will pay attention to instructions and even if you ask for YYYY/MM/DD, you will still get someone trying to use MM/DD/YYYY without even suspecting that your machine has an English Locale. It is strongly recommended that you always (even if you develop on the live machine, or one very similar) specify a <configuration>
<system.web>
<!-- Other settings here -->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-US"
uiCulture="en-US" />
</system.web>
</configuration>
Once you have done this, you know exactly where you stand. You can request the date in format MM/DD/YYYY format and if the user chooses to ignore that and use a culture-independent style then there is no harm done. If you do not specify a culture, even in the All of this applies equally to numerics in countries which take a comma (,) as a decimal point and to systems using different currency symbols. Another thing to watch out for is that if any of the values being compared are not of the type the validation is expecting (and in the case of dates, this includes DD-MMM-YYYY, eg. 10-Jan-2003), the form data will be considered valid. The reason for this is that an extra The CompareValidatorThe
ExampleIn the simple example, we can use this control to ensure that no one uses a specific E-mail address in the form (I mean, we don't want someone registering us for our own spam E-mail scam, do we?). Drop a When you run the application and try to enter your own email address into the form, the validator should give you a message as soon as you leave the As pointed out before, this is not entirely useful in itself; for the rare occasions you would use this, you would not mind hacking the Only when you start considering the combinations of the unique properties listed above do you realize how powerful this is. ControlToCompareInstead of comparing a control with a literal value, you can compare it to another user-entered string. You do this by pointing the If this and OperatorIt is not only possible to compare values for equality (or inequality), it is possible to look for In all cases, if the condition is true then the Alternatively, you can even check that the input data can be converted to a certain type, using the For example, when comparing two dates, if "F" is compared to "01/01/2003" then it is simultaneously considered to be greater than, less than and equal to. But when checking "F" using a When using The RangeValidatorThe With that in mind, the control's unique properties (not part of
ExampleReferring to our simple form, we can easily use a Replace whichever validator you are using with a Now any string entered that begins with a lower-case alpha character will be considered valid. Note again that if the MaximumValueThe value entered by the user may not be greater than this, but the two values can be equal. MinimumValueThe value entered by the user may not be less than this value (unless blank), but the two values can be equal. The RegularExpressionValidatorArguably the biggest, most versatile weapon in the ASP.NET validation arsenal has to be the With just one custom property over those provided by the
ExampleIn our simple example, replace the current validator with a Set the Whilst not perfect email address validation (see below), this is a pretty good approximation. It ensures that the address consists only of "word" characters (A-Z,a-z,0-9,_) with exactly one @ symbol and at least one period (.) after it, allowing for variations which include hyphenations in mid-word and extra periods before and after the @ symbol. Again, notice that a blank field is always valid unless you also use a ValidationExpressionThe data entered, if not blank, must match the format specified in regular expression format. This article will not attempt to cover regular expressions in detail, much has been written elsewhere on this site and others on this subject. Frankly, I do not claim to understand it that well, I usually manage with the default values provided by Visual Studio .NET or others that I find through Google (there are some fascinating expressions out there, if you look hard enough). The Visual Studio .NET default values can be found via the ellipses (...) button to the right of the property (within the property sheet) and offer the following validations:
There are some surprising omissions here (certain nationalities, US State Abbreviations, ISBN, Credit Cards, Long Date Formats), and some of the default expressions (inc. Email address) are not 100% accurate. The Regular Expression Library is the best resource I have found for most of those that are missing and for improving those that exist. If anyone has other resources, I would be happy to list them with the next update. The CustomValidatorSooner or later (probably later, to be honest), you are going to need to validate something and the standard validators are not going to offer it. Maybe you need to access a database, or perform some complex validation involving numerous controls. If you are going to need to do it repeatedly, you might want to consider creating your own validation control, but for the one-off oddity you can use the The You can populate the Other than that, it acts exactly the same as any other validation control, either showing the The
ExampleUsing our simple example once more, replace the validation control with a You can validate the value entered against a database, if you wish. For simplicity, I have chosen to simulate this with a simple private void alreadyInUse_ServerValidate(object source,
System.Web.UI.WebControls.ServerValidateEventArgs args)
{
// Default Value
args.IsValid = true;
// Simulating a check against a database
if (args.Value == "pdriley@santt.com")
args.IsValid = false;
}
The validator will always post back to the server to the NOTE: The ServerValidate (Event)As you can see in the example above, the The If there is no ClientValidationScriptWriting a JavaScript handler is conveniently similar to writing the server-side handler. It still exposes the same two arguments, The sample C# code above would directly translate as: function alreadyInUse_Validate (source, args)
{
// Default Value
args.IsValid = true;
// Simulating a check against a database
if (args.Value == "pdriley@santt.com")
args.IsValid = false;
}
All that is left to be done is set the The ValidationSummaryIt should be fairly clear by now that many web pages are going to include a lot of validation controls. No user is going to be happy with all those error messages popping up at random positions around the page, but it is always nice to have something marking the invalid fields. And this is where the The When a page is validated, all of the This finally explains the The
ExampleTo demonstrate the full power of the Consider a simple registration form for, say, a chat room. The customer requesting this form has asked for the following:
Set the form up yourself, complete with validators, using the rest of this article as a guide. As well as giving each control an error message, change the Although the Visual Studio .NET IDE will not allow you to drop validation controls directly on top of each other, you can edit the HTML view to force the controls into the same position. Along with the diagram, here is a clue: there are 12 validation controls in total:
Drop a Run the form and you can now see how a combination of validation controls and a If you get stuck then, again, the example is included in the downloadable zip file at the top of the article. DisplayModeThe list can be rendered in any of the following
The default option is EnableClientScriptBy default, If This is useful if (and only if) the HeaderTextAllows the definition of text to describe the list of errors. This will be posted directly before the list of error messages, regardless of the ShowMessageBoxIf set to The message box will emulate the style defined in ShowSummaryIf set to Either Bypassing validationIf you have two postback events (e.g.. "Next" and "Back" buttons), and one requires validation while the other does not, you can set the This will bypass both client and server validation. You can still check ConclusionThis is a very powerful set of controls with very few obvious dangers. As an added bonus, they are incredibly easy to implement. In Visual Studio .NET, it is just drag-drop and select a couple of properties. There is a lot of information to absorb in one pass, but hopefully this article will serve as a reasonably simple reference guide as well as a "How to" guide. Once you have used the validation controls a few times, you will be dropping them into pages just for fun. DownloadsSimply drop the files into any web application, include the .aspx files in the project and set anvindex.aspx as the start page. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||