Use Validation Control to Validate the User Input in .NET?

When the world only knew the ASP, there were certain things which were a real-time pain for the developers. They have to keep bending their back and screwing up their minds for validating the user input. User input had to be validated so that malicious use of pages could not be achieved so that incorrect or unwanted piece of information was not entered so that the information stored was standardized. This sounds only a painful job.

I am going to cover in depth all the validation mechanisms/techniques/controls we have available in our ASP.Net applications.

Why we use validation controls?

Validation is used to must always be validated user’s input before sending across different layers of the application. So it an important part of any web application

So the Validation controls are used to:

  • Implement presentation logic.
  • To validate user input data.
  • Data format, data type, and data range are used for validation.

Validation is of two types:

  1. Client Side
  2. Server Side

Since validation is of two types Server side and Client Side which is more than often done automatically whenever the need by reducing the workload of the programmer.

Client-side validation is good but we have to be dependent on browser and scripting language support.

Client-side validation is considered convenient for users as they get instant feedback. whenever the client validation is executed successfully then a page from being postback to the server.

You can use ASP.NET validation, which will ensure the client, and server validation. It works on both ends; first, it will work on client validation and then on server validation. At any cost, server-side validation will work in any condition whether client-side validation is executed or not. So you have safety of validation check.

For developer point of view serve side is preferable rather than client side because it will not fail and not dependent on browser and scripting language.

For client script .NET used JavaScript.

Validation Controls in ASP.NET

There are six types of validation controls in ASP.NET

  1. RequiredFieldValidation Control
  2. CompareValidator Control
  3. RangeValidator Control
  4. RegularExpressionValidator Control
  5. CustomValidator Control
  6. ValidationSummary

The below table describes the controls and their work

Validation Control Description
RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the value of another input control or to a fixed value
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified pattern
CustomValidator Allows you to write a method to handle the validation of the value entered
ValidationSummary Displays a report of all validation errors occurred in a Web page

So the following table describes the controls and their work of all validation in ASP.NET.

How to use Validation Control to validate the user input in.NET?

Let’s see an example of form validation. When a user submits data to our server through a web form we must check for various conditions, e.g

  • Email fields should have appropriate checks
  • Passwords should match

We will use client-side validation and server-side validation. You must be careful and do not make the mistake to have only client-side validation. You must always validate your data on the server side. In fact, you should use both client side and server side validation. It is not very difficult to bypass client-side validation.

Since with client-side validation, we can reduce unnecessary round trips to the server. By that, we make our application more responsive and the user will get immediate feedback.

RequiredFieldValidator

RequiredFieldValidator control is used to checks data is entered into the attached control. The syntax of the required Field control is as given:

<asp:RequiredFieldValidator ID="rfvcandidate" 
   runat="server" ControlToValidate ="ddlcandidate"
   ErrorMessage="Please choose a candidate" 
   InitialValue="Please choose a candidate">
   
</asp:RequiredFieldValidator>


Example:

In this example, I create two textboxes for username and password. If I submit the form without filling username and password then the page show errors( Please enter a username and Please enter password).

RequiredFieldValidator.aspx (Design Page):

RequiredFieldValidator.aspx (source code):

<%@ Page Title="" Language="C#" MasterPageFile="~/RoseindiaMaster.master" AutoEventWireup="true"
CodeFile="RequiredFieldValidator.aspx.cs" Inherits="RequiredFieldValidator" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
<h2 style="color: Green">
RequiredFieldValidator in ASP.NET 4 , C#</h2>
<br />
<table cellpadding="0" cellspacing="0" style="height: 177px; width: 246px">
<tr>
<td><strong>User Name:</strong></td>
<td><asp:TextBox ID="userTextBox" runat="server" Font-Names="Verdana" /></td>
</tr>
<tr>
<td colspan="2"><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please enter user name." ControlToValidate="userTextBox" ForeColor="Red" ValidationGroup="Submit">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<strong>Password: </strong>
</td>
<td>
<asp:TextBox ID="passwordTextBox" runat="server" 
TextMode="Password" Font-Names="Verdana" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
ErrorMessage="Please enter password."
ControlToValidate="passwordTextBox" ForeColor="Red" ValidationGroup="Submit">
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td> </td>
<td><asp:Button ID="submitButton" runat="server" Text="Submit" Width="80px" 
onclick="submitButton_Click" ValidationGroup="Submit" /></td>
</tr>
<tr>
<td colspan="2"><asp:Label ID="Label1" runat="server" Font-Bold="True" 
ForeColor="#000099"></asp:Label> </td>
</tr>
<tr>
<td colspan="2"><asp:Label ID="Label2" runat="server" Font-Bold="True" 
ForeColor="#000099"></asp:Label></td>
</tr>
</table>
</div>
</asp:Content>


RequiredFieldValidator.aspx.cs (C# code file):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class RequiredFieldValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
Label1.Text = "User Name : " + userTextBox.Text;
Label2.Text = "Password : " + passwordTextBox.Text;
userTextBox.Text = "";
passwordTextBox.Text = "";
}
}

Output:

 

CompareValidator

Compare validator is used to compare the value of two controls or with a fixed value. It has the following specific properties:

Properties Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input control to compare with.
ValueToCompare It specifies the constant value to compare with.
Operator It specifies the comparison operator, the available values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.

Example:

This example demonstrates you how can we compare to date field using asp.net compare validator control. if user inputted date does not match in both textboxes then validation fails and the browser shows a validation error message. if both textbox text matches then validation success. In this example I compare the current date with the date entered by user..however, I’m encountering errors so far…

I tried something like this:

<asp:TextBox id="txtDate1" runat="server" />    
<asp:CompareValidator runat="server" ErrorMessage="The date must be greater than today"
    ControlToValidate="txtDate1" type="date" 
    ValuetoCompare="DateTime.Today.ToShortDateString()" />

RangeValidator Control

Range validator is used to validate the input value falls within a predetermined range.

Example:

This example demonstrates you how can we set the range of text field using asp.net Range validator control. if the user inputted text range is not between 6-12 then validation fails and the browser shows a validation error message. if textbox text is between 6-12 then validation success.

I tried something like this:

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass" 
   ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" 
   MinimumValue="6" Type="Integer">
   
</asp:RangeValidator>

RegularExpressionValidator

The RegularExpressionValidator is used to validating the input value by matching against a pattern of a regular expression and it is set in the ValidationExpression property.

The syntax of the Regular Expression control is as given:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
   ValidationExpression="string" ValidationGroup="string">
   
</asp:RegularExpressionValidator>

The following table summarizes the commonly used syntax constructs for regular expressions:

Character Escapes Description
\b Matches a backspace.
\t Matches a tab.
\r Matches a carriage return.
\v Matches a vertical tab.
\f Matches a form feed.
\n Matches a new line.
\ Escape character.

CustomValidator

The custom validator is used both the client side and the server side validation. It allows writing application-specific custom validation routines.

The basic syntax for the control is as given:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
   ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
   
</asp:CustomValidator>

ValidationSummary

Validation summary does not perform any validation but shows a summary of all errors on the page. It has the following specific properties:

Properties Description
ShowSummary shows the error messages in a specified format.
ShowMessageBox shows the error messages in a separate window.

The syntax for the validation summary control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" 
   DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

How good or bad asp.net validation controls are??

 

So now let’s see both sides of the coin as to whether these are advantageous or not so beneficial for the developers and on the whole.

Advantages:

  • Minimum code writing for Client/Server Side.
  • Facility of assigning a particular validation to a particular control.
  • The ways of reporting the user about the validation error are multiple.
  • Having the knowledge of JAVA is not necessary.
  • Only particular validations will fire for specific areas of the screen by grouping validations and controls.
  • Provide the facility of custom validation to control other validations.
  • With benefits, these many Validation Controls look all good and it would seem like a waste of time to go to the argument of listing down the not so good aspects of it. But we will do it anyway to get into the detail of the matter.

Disadvantages:

  • Writing all the validations by yourself, a tedious task.
  • Write code even to display an error on the screen.
  • Coordinating amongst various developers to be consistent with all the error messages across various platforms.
  • You have knowledge of JavaScript and ASP.NET.

So it seems like there are more benefits than the disadvantages. Giving the programmers a bit of a relief from the extra botheration they had before.

ASP.Net Validation Controls – Always use the ValidationGroup property

Suppose I had an ASP.Net control that would not a postback, no matter what I tried.

I have a page with several user controls on it.  One of these user controls is an asp: Textbox. This textbox hooked to some JavaScript. So when the user clicks “enter” in that control a postback will occur. Some JavaScript accomplished postback. The postback calls the click event on a button i.e. hidden (style=” display: none”).  But the postback wouldn’t work.  I put a few alerts in the JavaScript. I knew it was getting called, but the postback still never occurred. Since the problem was not so easy to see.  That’s because I had a second user control on the page. So That second user control has an asp: RequiredFieldValidator in it. So that to complicate things that validation control was tucked in a modal popup (using the Ajax Control Toolkit’s Modal Popup Extender).  But, I forgot to include the ValidationGroup property in the validator.

So any control on the page would cause validation to occur which will block the postback if validation fails.  But since the validator was in the popup (which of course, was not currently popped up). So, I didn’t see the error message that was trying to tell me there was a problem.

The problem easily fixed (if not easily found) by simply adding the ValidationGroup property to the validator and of course, matching it up on the button that is supposed to call that validation group.

Conclusion:

So Validation controls provide the necessary functionality for any Web development. This is a great improvement over the basic ASP technology. So, I hope this article has provided the groundwork for employing the validation controls in your next development project. Since validation controls make a developer’s life a lot easier. So, validation and Web controls make an outstanding combination for building smart forms.

 

Get in Touch

Leave a Comment