Quite often there is a difference in how a developer tests a web form and how a user uses it. Users may:

  • leave random characters in a field that requires a telephone number to be the input. For example, if there is a code that tracks phone calls and compares them to the phone data sent through the web forms, it can be a huge problem (or an impossible task) for the developer to find out which numbers should have been put in the place of those random characters.
  • leave important fields empty.
  • make a typo or confuse an input field for another input field.
  • intentionally or unintentionally enter characters that completely break the code and possibly even gain access to data from the data base (SQL injections are the typical example of malicious code used for gaining such access).

Above are just examples. The more complicated the form is and the more unexperienced the users are, the larger is the possibility of some incorrect input to cause headache to the developers. Thus validation must be used.

In normal Windows applications, for example, if a user enters a letter in a number only field, the application handles the KeyPress event and prevents the input character to appear in the field because it’s not a valid one.
This doesn’t work as easy in a server-side web page. The correct approach is to perform all the validations at once, right after a form is submitted. ASP .NET provides 5 validation controls that can be used:

  • RequiredFieldValidator – checks if the input is not an empty string.
  • RangeValidator – checks if the input is inside some numeric, alphabetic or date range.
  • CompareValidator – checks if the input is the same as another input or as some predefined value. Often used (alongside with other validations) while validating passwords.
  • RegularExpressionValidator – checks if the input matches a specific regular expression (or simply RegEx). This can be used to validate phone numbers, emails, passwords, postal codes or anything that has a specific format.
  • CustomValidator – developers create the logic for this one.

Each validation control can be bound to one input control, but one input field can be validated by several validation controls.
A good practice is to provide some user interface for feedback about the success of validation. For example, a list of all the fields that the user needs to fill in in order for the validation to succeed; or a message that the validation has been successful. Additionally, this feedback can be enriched using Javascript.

Validation Control Properties

There are several properties that define the basic functionality of validation controls:

  • ControlToValidate – identifies the control to validate.
  • ErrorMessage – message to be displayed if the validation fails.
  • ForeColor – used for defining the colour if the error message.
  • Display – this provides 3 message display options: Dynamic display that dynamicaly inserts the error messages into the page; Static display that displays the messages in some previously reserved space on the page (often looks ugly if we have multiple validation messages, so it’s usually used when these messages are small number or the page has some specific style that suggests the usage of Static dislpay); None – the message is hidden.
  • IsValid – returns true/false depending on the success of the validation.
  • Enabled – if set to “false”, no automatic validation will be performed for this control.
  • EnableClientScript – if set to “true”, it will add default Javascript and DHTML on all modern browsers. This additional code is used for client-side validation.

There are also some Validator specific properties that must be used only on some of the validators and cannot be used on all of them like the ones above:

  • MaximumValue – used on RangeValidator.
  • MinimumValue – used on RangeValidator.
  • Type – used on RangeValidator and CompareValidator.
  • ControlToCompare – used on CompareValidator.
  • Operator – used on CompareValidator.
  • ValueToCompare – used on CompareValidator.
  • ValidationExpression – used on RegularExpressionValidator.
  • ClientValidationFunction – used on CustomValidator.
  • ValidateEmptyText – used on CustomValidator.
  • ServerValidate – used on CustomValidator. An event that occurs when the validation is performed on the server.

RequiredFieldValidator has no validator specific properties.

Examples of Validator Usage:

<asp:TextBox ID="txtEmail" runat="server" />
// Requires an email to be entered in the field txtEmail
<asp:RequiredFieldValidator id="vldEmail" runat="server" 
ErrorMessage="You must enter an email." ControlToValidate="txtEmail" />

<asp:TextBox ID="txtPassword" TextMode="Password" runat="server" />
<asp:TextBox ID="txtRetypePassword" TextMode="Password" runat="server" />
// Requires the re-entered password in the field txtRetypePassword to match the 
// one in txtPassword
<asp:CompareValidator id="vldRetypePassword" runat="server" 
ErrorMessage="The password does not match." ControlToCompare="txtPassword" 
ControlToValidate="txtRetypePassword" />

<asp:TextBox ID="txtZIP" runat="server" />
// Checks if the data entered in txtZIP is a valid US ZIP code. "\d{5}(-\d{4})?" 
// means we need 5 starting digits with an optional extension of 4 digits – 
// like: 36597 or 22335-9012
<asp:RegularExpressionValidator id="vldZIP" runat="server" 
ErrorMessage="This ZIP code is not in the correct format." 
ValidationExpression="\d{5}(-\d{4})?" ControlToValidate="txtZIP" />

<asp:TextBox ID="txtMonth" runat="server" />
// Checks if the entered numeric value is a valid month
<asp:RangeValidator id="vldMonth" runat="server" 
ErrorMessage="The month must be between 1 and 12." Type="Integer" 
MinimumValue="1" MaximumValue="12" ControlToValidate="txtMonth" />

<asp:TextBox ID="txtHello" 
placeholder="Please start your sentence with Hello." runat="server" />
// A custom validator
<asp:CustomValidator id="vldHello" runat="server" 
ErrorMessage="Enter a sentence that starts with Hello" 
ValidateEmptyText="False" OnServerValidate="vldHello_ServerValidate" 
ControlToValidate="txtHello" />

// This is used for the CustomValidator above
protected void vldHello_ServerValidate(Object source, ServerValidateEventArgs e)
{
    try
    {
        // Check whether the input string starts with "Hello".
        String val = e.Value.Substring(0, 5);
        if (val == "Hello")
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }
    catch
    {
        // An error occurred in the process.
        // The input is not valid.
        e.IsValid = false;
    }
} 

Was this post helpful?