Working with Input Validation Controls in ASP.NET 3.5



Introduction: A common use of web pages is to collect information from a user and to store it in a back-end database; what is important and common is to validate the user input data before the server processes it.

Although this validation can happen at the server side, ideally to save the server resources, the validation of input should happen at the client side, by which it can give the user faster feedback.

If validation is done manually by writing code to handle it, it can be a lengthy task. Especially since the models for client side are typically programming using JavaScript; server side programming by ASP.Net is quite different. So the solutions are Validation Controls. They can be declared on a web form and then bound to any other input control.

What all we can validate: ListBox, DropDownList, RadioButtonList, HtmlInputText, HtmlTextArea, and HtmlSelect.

What we cannot validate: RadioButton or CheckBox controls

Process of Validation: we can ideally use validation controls to verify a page automatically when the user tries to click the submit button. Every button has a CauseValidation property, which can be set to True of False.

If True: ASP.NET will ignore the validation controls.

If False: ASP.NET will automatically validate the page when the user clicks the button. It does this by performing the validation for each control on the page. This is the default.

Who is the Base class of the validation control?

The validation control classes are found in the System.Web.UI.WebControls namespace and inherit from the BaseValidator class.

So let us take each validation control and program it in the manner it offers.

First, follow the steps below to create a user input form.

Step 1: Create an ASP.NET Website and name it "ValidationControls".

Step 2: Create a table and input the control like below:

asp.net1.gif

1. Name: RequiredFieldValidator

Server Tag : <asp:RequiredFieldValidator>
Purpose: Checks that the control it validates is not empty when the form is submitted.

Select the Required Field Validator from the Toolbox and drag it to the textbox.

asp.net2.gif


<asp:TextBox runat="server" Width="200px" ID="Name" />
<asp:RequiredFieldValidator ID="ValidateName"
     ControlToValidate="Name"                        
     runat="server" ErrorMessage="Name is Required"
     Display=Dynamic>
</asp:RequiredFieldValidator
>

This is pretty straight; we can do the same for other textboxes.

2. Name: Range Fields Validator

Server Tag : <asp:RangeValidator>

Description: Checks that the value of the associated control is within a specified range. The value and the range can be numerical; either a date or a string.

We can use this to allow the user to input Date Off between a specified DateTime, say between 08/05/08-08/20/08. So let's drag a range Validator next to the Date Off textbox.

<asp:TextBox runat="server" Width="200px" ID="DayOff" />
<asp:RequiredFieldValidator runat="server" ID="ValidateDayOff"      ControlToValidate="DayOff" ErrorMessage="Day Off is required"
     Display="dynamic">*
</asp:RequiredFieldValidator>
<
asp:RangeValidator ID="ValidatedateOff2"
     ControlToValidate="ValidateDayOff"
     ErrorMessage="Date off is not within the valid interval"
     MinimumValue="08/05/2008"
     MaximumValue="08/20/2008"
     SetFocusOnError="true"
     Display="Dynamic"
     runat="server"
></asp:RangeValidator
>
3. Name : CompareValidator

Server Tag: <asp:CompareValidator>
Description: Checks that the value of the associated control matches a specified comparison (less than, greater than, and so on) against another constant value or control.

Using this validator we can ask user to input a age greater than 18, i.e. > 18

<asp:TextBox runat="server" Width="200px" ID="Age" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Age"      ErrorMessage="Age is required" Display="dynamic"
     ID="Requiredfieldvalidator1">*
</asp:RequiredFieldValidator>
<
asp:CompareValidator
ID="CompareValidator2" runat="server"                                               
     ControlToValidate="Age"
     ValueToCompare="18"
     Operator="GreaterThanEqual"
     ErrorMessage="You must be at least 18-year-old"
     Display=Dynamic
     Type=Integer>             
</asp:CompareValidator>

You notice here we have many operators to use, we have used GreaterThan Equal:

asp.net3.gif

Similarly , we can assign Type of value with which we are comparing.

asp.net4.gif

We we can do the same for a password; that is, to compare with a password that should match.

<asp:TextBox runat="server" TextMode="Password" Width="200px" ID="Password2" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Password2" ErrorMessage="Password2 is required"                                    Display="dynamic"
      ID="Requiredfieldvalidator4"
      Name="Requiredfieldvalidator4">
<img src="imgError.gif" alt="Missing required field." />
</asp:RequiredFieldValidator>
<
asp:CompareValidator runat="server"
   ControlToValidate="Password2"
   ControlToCompare="Password"
   Type="String"
   ErrorMessage="The passwords don't match"
   Display="dynamic"
   ID="Comparevalidator1"
   Name="Comparevalidator1">
<img src="imgError.gif" alt="Fields don't match." />

</asp:CompareValidator>
Notice that we have set ControlToValidate = "Password2" and have used ControlToCompare = "Password".

4. Name: RegularExpressionValidator

Server Tag : <asp:RegularExpressionValidator>
Description: Checks if the value of the control it validates matches the specified regular expression. They allow you to specify complex rules that specify the characters, and in what sequence (position and number of occurrences) they are allowed, in the string. For example, the following control checks that the text input in the text box is a valid e-mail address:

So here we will try to validate the email textbox, using the regular expression validator.

<asp:TextBox runat="server" Width="200px" ID="Email" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Email"      ErrorMessage="E-mail is required" Display="dynamic"
     ID="Requiredfieldvalidator2">*
</asp:RequiredFieldValidator>
<
asp:RegularExpressionValidator runat="server"
    ID="ValidateEmail"
    ControlToValidate="Email"
    validationExpression=".*@.{2,}\..{2,}"
    ErrorMessage="E-mail is not in a valid format"
    Display="dynamic">*
</asp:RegularExpressionValidator
>

Now here we have to concentrate on our validation expression : =".*@.{2,}\..{2,}

The expression .*@.{2,}\..{2,} specifies that the string that it's validating must begin with a number of characters (.*) and must contain an @ character, at least two more characters (the domain name), a period (escaped as \.), and, finally, at least two more characters for the domain extension.

But yes regular expressions do not validate domain name.

Let us try to invest more time here; we can also design more complex expressions in addition to single characters. We can specify a class or a range of characters that can be matched in the expression. We can specify that a certain character or class of characters must be present at least once, or between two and six times, and so on.

Consider this expression
[aeiou]{2,4}\+[1-5]*

Explanation: string should start with two to four vowels, have a + sign, and terminate with zero or more digits between 1 and 5.


5. Name: CustomValidator

Server Tag : <asp:CustomValidator>
Description: Allows you to specify any client-side JavaScript validation routine and its server-side counterpart to perform your own custom validation logic. CustomValidator allows you to execute your custom client-side and server-side validation routines. The client-side and server-side validation routines for the CustomValidator are declared similarly.
They both take two parameters: a reference to the validator and a custom argument object.

Let's say we want to validate textbox ID to be a multiple of 5, so for this we will create our own custom validator; one at client side and another at server side.

<asp:TextBox runat="server" Width="200px" ID="EmpID" />
<asp:RequiredFieldValidator runat="server" ID="ValidateEmpID" ControlToValidate="EmpID" ErrorMessage="ID is required"
Display="dynamic">*
</asp:RequiredFieldValidator>
<
asp:CustomValidator runat="server" ID="ValidateEmpID2"
    ControlToValidate="EmpID"                                                  ClientValidationFunction="EmpIDClientValidate"
     ErrorMessage="ID must be a multiple of 5"
     Display="dynamic"                                    OnServerValidate="ValidateEmpID2_ServerValidate">*
</asp:CustomValidator
>

The client side JavaScript function is as below:

<script type="text/javascript">
      function EmpIDClientValidate(ctl, args)
      {
 
        // the value is a multiple of 5 if the module by 5 is 0
        args.IsValid=(args.Value%5 == 0);
      }
    </script>


And the server side validation handler is as below:

protected void ValidateEmpID2_ServerValidate(object source, ServerValidateEventArgs args)
        {
            try
            {
                args.IsValid = (int.Parse(args.Value) % 5 == 0);
            }
            catch
            {
                args.IsValid = false;
            }
        }

6. Name : ValidationSummary

Server tag: <asp:ValidationSummary>
Description: Shows a summary with the error messages for each failed validator on the page (or in a pop-up message box). This actually doesn't perform any validation. The summary display error message for each failed validation for validator controls.

<asp:ValidationSummary runat="server"
           ID="Summary"
           DisplayMode="BulletList"
          HeaderText
="<b>Please review the following errors:</b>"

     ShowSummary="true" />

 
That is all for here, so finally we can write code for the Submit Button click:

protected void Submit_Click(object sender, EventArgs e)
      {
            if (Page.IsValid)//If everything is fine.
                  Result.Text = "Thanks for sending your data";
            else
                  Result.Text = "There are some errors, please correct them and re-send the form.";
      }

 

Up Next
    Ebook Download
    View all
    Learn
    View all