Validation

In order to help users avoid making mistakes, we can provide them with feedback on invalid input using ASP.NET's Validation features

Getting started

  1. Download or fork the starter project with validation missing from GitHub and open it
  2. With later versions of ASP.NET, a little setup needs to be done within a project to enable validation to work - in short, the validation controls rely on jQuery, and so a jQuery Script resource needs to be configured for the project. Add the necessary code using the instructions at this link

The Required Field validator

  1. Open the SetUserName.aspx page in the starter project and consider the code in the aspx file. You will notice that there is already a textbox for the user to enter a username, but if the box is left blank, and the button pressed a server error will be displayed (commonly known as the 'yellow screen of death'). This error is not particularly helpful for the user, and it would be better to provide them with some feedback on the form itself to advise them what to do.
  2. One of the simplest validators available in ASP.NET is the RequiredFieldValidator. This allows us to ensure that a user does not leave a field blank. To do this we need to add the required field validator to the aspx page, and tell it which field it should be associated with. Drag a required field validator from the Validation section of the toolbox, onto the page directly after the Text Box.
  3. In code view, the required field validator should appear as show below:
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
  4. We need to make a few changes in order for this required field validator to work. Firstly, change the ID of the validator so it is more meaningful, by setting it to something like reqValUsername
  5. Secondly, in the properties for the validator, locate the ControlToValidate property and set it to the id of the text box, in this case txtName.
  6. WCAG 2.0 guideline 3.3.1 states “If an input error is automatically detected, the item that is in error is identified and the error is described to the user in text.”, and guideline 3.3.3 states: “If an input error is automatically detected and suggestions for correction are known, then the suggestions are provided to the user, unless it would jeopardize the security or purpose of the content.”

    Next, change the error message to something that both inform the user of their error, and advise how to rectify the issue.
  7. The code for the validator should now look something like this:
    <asp:RequiredFieldValidator ID="reqValUsername" runat="server" ErrorMessage="Username field cannot be left blank, please enter a name" ControlToValidate="txtName"></asp:RequiredFieldValidator>
  8. Now try and use the form without entering a username, instead of the yellow screen of death, a helpful message will be displayed to the user.
  9. At this stage, the validator will be firing in JavaScript, however if the user were to have JavaScript turned off (or you did not include jQuery in your project), then it would not work. Validation should work regardless of a user's decision to not use JavaScript. To ensure it works for all users, we need to add some code to the button's event handler. Open SetUserName.aspx.cs file and add the code shown in bold below (be sure not to miss the final closing brace):
    protected void btnSetUsername_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            DataProcessor processor = new DataProcessor();
            processor.SetUserName(txtName.Text);
            divSetUserName.Visible = false;
            divSuccess.Visible = true;
            
        }
    }

The Range Validator

  1. Open the Salary.aspx file.
  2. Try adding a negative value to the field and clicking the calculate button - you will see a yellow screen of death
  3. In a similar way to how you added the required field validator, add a range validator, and set its ControlToValidate and ErrorMessage properties
  4. The range validator also needs to know a minimum and maximum value for the field it is validating, and the type of data (Currency, Date, Double, Integer or String) Set the MinimumValue, MaximumValue and Type properties
  5. Ensure you add code to the event handler in Salary.aspx.cs (as you did for the previous form)
  6. Test your form to check that valid salaries can be input, and that the error is displayed when invalid data is input - be aware that whilst the type should be set to Currency, the validator does not allow you to enter the "£" symbol in the box - ensure your users are informed of this in the error message
  7. Finally be aware that the range validator restricts the type of data that can be input - therefore if the range of acceptable values in a form can be predetermined, it can be useful for restricting input to certain types.

The Regular Expression (Regex) Validator

Some forms of input are less than simple to check for validity, for example phone numbers (as they are not really numbers, rather a string a of digits), post codes, national insurance numbers and email addresses. Regular expressions can be used to provide a set of rules that data must be follow, for example a post code might start with either one or two letters, be followed by a number, then optionally either a number or letter, then a space, then one number and two letters. A regular expression (or Regex for short) to accomplish this might appear as follows: /[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/gi;.

The good news is, we rarely have to create these regular expressions ourselves, because unless we are looking for some proprietary pattern, there's a good chance someone else has created one and made it available on the web. If you use a regular expression in an assignment for academic work sourced from a third party, make sure you include a comment referencing it in your code, and a suitable reference in any documentation

  1. Open the RegisterPhone.aspx file, and add a RegularExpressionValidator at the appropriate point. Set a helpful error message and ensure that it is configured to validate the correct control
  2. Using the web, search for a regular expression validator for a UK mobile phone number. You can assume that it will be 11 digits in the form (07123456789) (e.g. ignore versions starting +44)
  3. Set the regular expression for the validator
  4. Add the appropriate code to the event handler in the .cs file and test the form with some invalid and valid phone numbers.

The Compare Validator

Sometimes we want to check the value of one field against another, this might be to check they are equal (for example confirming a password so a user does not sign up with a mistakenly typed password), not equal (to force a user to change a password to a new one), or even to check that one field's value is greater than another (for example start and end dates for an event)

  1. This first task will check that two passwords entered match - this is particularly important as many browsers obscure the password, so the user cannot see what has been typed. Open the Register.aspx file to start
  2. Drag a CompareValidator from the toolbox to an appropriate place on the page
  3. As before, set the ControlToValidate property to the txtPassword field and ErrorMessage properties appropriately
  4. The compare validator also has a ControlToCompare property - set this to the txtConfirmPassword field
  5. Verify that the Operator property is set to Equal (the passwords must match)
  6. Add the appropriate code to the event handler in the .cs file
  7. Test the form with both matched and mismatched passwords

Other comparison checks

  1. Open the ChangePassword.aspx file. Add and configure a CompareValidator so that the user cannot use the same password again. Test the validator.
  2. Open the MPGInput.aspx file, ensure that the user must enter the lowest value for Urban MPG, and highest for Extra Urban MPG, with combined in the middle. Test your solution

The compare validator also allows you to specify a ValueToCompare property instead of another control. This is useful for comparing against set values - for example checking a date is not too far in the past

Multiple validation fields and validation summary

Quite often, we may need to validate multiple fields on a page, some of the with multiple validators. In order to keep things simple, we can provide a summary of validation issues on the page using the ValidationSummary control.

So far we have specified our error messages inside the ErrorMessage property, however if we add text between the opening an closing tags of the validator, this text will appear at the location of the validator, whereas the error message will appear in the summary. When using a validation summary, convention indicates that we use an asterisk to indicate invalid fields, whilst providing a description of the error in a summary. See the code below for an example of how we might configure a validator for this purpose:

<asp:RequiredFieldValidator ID="reqValName" runat="server" ErrorMessage="Name is a required field">*</asp:RequiredFieldValidator>

  1. Add all the necessary validation to the ComplexForm.aspx page, and use a summary to provide validation messages.
  2. Ensure you add the necessary code to the .cs file, and test the form with a variety of valid and invalid data.