Session 3 - Validation
A vital aspect of any application is to make sure that data entered by a user is valid. In a web appication it is possible for some validation to be performed before
the data is sent to the server using client side scripts (e.g. data must be in the correct format, or an email address needs an '@' symbol and at least one '.'). Other data may need to be checked by the server once it has been submitted (e.g. check
for a valid user ID). ASP.Net provides a set of elements (Validation Controls) which can be linked to data entry elements to provide validation within the page. Validation
can be performed on the client (in some cases), or on the server. Various kinds of validation can be performed from simply checking that something/anything has been typed to checking complex patterns of letters and digits (e.g Postcode or ISBN).
Each validation control has an 'ErrorMessage' property and a 'ControlToValidate' property. You simply type a suitable message in the ErrorMessage property, which will be displayed if the data is invalid. You select the element from your page which you want to validate on the ControlToValidate property.
Simple Example of validation
We will modify the Professional website to check that the user has typed a name before clicking the Send button.
Step by step
If you want to keep your original simply copy the contents of the Professional folder to a new folder called E:\Web\SimpleValidate.
- Open your website (Professional or SimpleValidate).
- In the toolbox pane scroll down to the Validation section and expand it.
- Drop a RequiredFieldValidator to the right of the Textbox.
- Change the id of the control to 'validName'.
- In its properties change the value of ErrorMessage to 'You must type your name!'.
- In its ControlToValidate property select txtName from the dropdown list.
- Save your project and click Run
If you click 'Send' before typing anything you will see a message in red telling you that you need to type your name. Type your name and click 'Send' and now the page will display the Hello message with your name. Try out the
SimpleValidate
example or download the
Zip version of SimpleValidate.
Using the other basic validation controls
The other controls you can use are:
- RangeValidator
The RangeValidator allows you to specify a value type (string, integer, date, currency
or double) and a minimum and maximum value. If the entered data is not within the prescribed range (or type) then the error message is displayed. For example, integers
in the range 2000 and 2020. - RegularExpressionValidator
The RegularExpressionValidator uses the power of a mathematical technique called regular expressions to specify complex character sequences to validate against. The property ValidationExpression can be set to one of a predefined list of (mainly American) expressions, but you can also type in your own. Unless you are familiar with the mathematical technique your best bet is to do a Google search for example regular expressions. There are lots of websites specialising in regular expressions with lots of examples. - CompareValidator
The CompareValidator allows you to specify another value to compare the ControlToValidate against. This can be a typed value, a data type or another control (ControlToCompare). This is useful for Password forms where you need to verify that both copies of the typed password are the same. (For password fields make sure you change the type of the textboxes to password so that the value is hidden (behind *'s) when you type.)
Look at Web application
ValidateDemo
for an example of each type of validation control or download a
Zip version of ValidateDemo.
Advanced validation
The above validation controls all perform a single validation task, and annotate a control with an error message. The validation can be performed on the client if the browser permits it. However, an application may have more advanced validation needs which may require processing on the server. Also some form of validation summary on a page can be useful. Both of these are available. The CustomValidator control allows the application developer to write a script to perform the validation. The ValidationSummary Control does just what it says; it summarises the validation elements on a webpage.
How to use the ValidationSummary control
In its basic form you simply drop the ValidationSummary control onto your webpage in a suitable location. The control gets filled with the list of error messages from all the other validation controls on the page.
Take a look at application
ValidateSummary
or download a
Zip version of ValidateSummary.
How to use the CustomValidator control
Custom validation by its very nature implies that it will only work if you provide
a script to perform the validation. Various circumstance may prohibit you from using
one of the other validation controls. For example, a value may need to be validated against a list stored in a database, or a set of values may need to be verified
against specific valid combinations.
To demonstrate this we will produce a simple web application which allows you to
choose three presents from a list. This will also give us the opportunity to look
at how we use scripts with lists.
To build this application we will need a web form with a ListBox list on it, a CustomValidator,
a Button and a Label. We can edit the items in the ListBox at design time and modify
its properties to allow multiple select. The label will be used to display the selected
items, but in more realistic scenario these may be entered onto a database.
As mentioned earlier other validator controls may perform validation on the client, rather than
posting the form back to the server. This depends on the settings and version of
the client browser. The CustomValidator control, however, only works server
side, as the custom code needs to be executed to make the validator work.
We can force the server to perform validation by selecting the 'CausesValidation'
property on the ListBox to true, or we can explicitly request the page to validate
itself using the Page.Validate() method.
Either way we can check the result of validation using the Page.IsValid. We can decide
whether to perform any page actions dependent on the value of Page.IsValid.
Step by Step
- Create a new C# Web site called CustomValidate.
- Drop a ListBox, a CustomValidator, a Button and a Label onto the form and change
their (ID)s to lbPresents, validPresents, butSend and labSelection.
- Select the CustomValidator and select lbPresents from the dropdown list in the ControlToValidate property.
- Set the ErrorMessage property to 'You must select three presents'.
- Build some text
around the controls to make the user interface more appealing. For example:
- Double click the CustomValidator control. This should bring up the C# script view for the page and create an empty event handler for validation called 'validPresents_ServerValidate'.
- One of the arguments for the event handler is called 'args'. This has a field called 'IsValid'. If you set this to false then the ErrorMessage will be displayed. If you set it to true then the page passes its validation test and the error message is not displayed. So the pseudo code for our validation script is:
Set args.IsValid to False;
Count the number of selected items in the list.
If there are three, set args.IsValid to True;
- This converts to C# code as follows:
protected void validPresents_ServerValidate
(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
int numselected = 0;
foreach (ListItem li in lbPresents.Items)
{
if (li.Selected)
{
numselected++;
}
}
if (numselected == 3)
{
args.IsValid = true;
}
}
- Now the only problem is that because it is the server working out whether the information is valid we need to cause the page to validate and put a check in to
make sure it is valid before filling in the message on the label. The code could
be done in an event handler for the Button, but since this is a very simple application
we can put the code in the Page_Load method, as follows:
protected void Page_Load(object sender, EventArgs e)
{
labSelection.Text = "";
Page.Validate();
if (Page.IsValid)
{
foreach (ListItem li in lbPresents.Items)
{
if (li.Selected)
{
labSelection.Text =
labSelection.Text + " - " + li.Value;
}
}
}
}
You can try out
CustomValidate
or download the
Zip version of CustomValidate.
Session 3 - Workshop
- Modify your answer to Session 2 - Workshop, exercise 2 to include validation.
- Modify the Email applications to validate the text boxes. For example, text
boxes with email addresses in them will need a RegularExpressionValidator and a
RequiredFieldValidator