Home Page

Click here to download the sample source code for this lesson

A very common requirement for many web applications is validating user input.  ASP.NET helps improve developer productivity in the area of validation by offering a set of server controls called Validation Controls.  Validation controls do not require any coding, thus saving time performing redudant tasks.  These controls are a little different than the server controls that we examined in prior lessons.  The validation controls are normally hidden on the web page, unless a validation error occurs, at which time they display an error message alerting the user of the validation failure.  They are also similar to other server controls in the way you drag them from the Toolbox window onto your web form and then set the necessary properties to control how the validation controls will behave.

In this exercise we will cover how to ensure that the user typed information into required fields (i.e. fields that must be filled out) before the form is submitted to the server.  This helps prevent null or empty data from getting into the database whenever the fields are mandatory.  A very common example of a requirement to use required fields is a website registration form.  Most websites require that you fill in some mandatory set of fields when registering, such as first name, last name, etc.

ASP.NET offers the RequiredFieldValidator control to ensure that mandatory fields are filled in.  The RequiredFieldValidator is very easy to use; just drag it from the Toolbox window onto your web form.  It is located in the Validation group in the Toolbox window, so you may have to scroll down the Toolbox to find it.  You should drag the control to the location where you want the error message to show up, in case the validation fails; which in this case is if something isn’t entered into a field.

Once you have dragged the validator onto the web form, you need to set a couple of properties.  The ErrorMessage property sets what error text will be displayed in case the validation fails.  The error text will be shown in red.  The other property to set is the ControlToValidate, which lets the validator control know which server control to examine at runtime to see if it’s empty or not.

Click here to watch an example video.  In the example I dragged a RequiredFieldValidator next to the First Name TextBox control.  Notice that I changed the error message to “First Name is required” and the ControlToValidate to txtFirstName which is the ID of the First Name TextBox.  When I run the program, if I don’t type anything into the First Name field, notice that the error message is displayed.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment