//
you're reading...
ASP.NET

Working with Input Validation Controls in ASP.NET 3.5

Working with Input Validation Controls in ASP.NET 3.5

Introduction: A common usage of web pages is collect information from user, and store it in a  back end database, what is important and common is to validate the user input data before server can process on it.

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

If validation is done manually by writing code to handle, it can be a lengthy task. Especially because the models for client side are programming typically by JavaScript and server side programming by asp.net are quite different. So the solutions are Validation Controls. They can be declared on 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 control to verify a page automatically when user try to click submit button. Every button has 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 default.

Who is the Base class of 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 of validation control and programs them as per their offerings.

Before this follow below steps to create a user input form

Step1: Create an ASP.NET Website and name is “ValidationControls”.

Step2: Create a table and input control like below

1)    Name: RequiredFieldValidator

Server Tag : <asp:RequiredFieldValidator>

Purpose: Checks that the control it has to validate is not empty when the form is submitted.

Select Required Filed Validator from Toolbox , and drag it to name textbox.

<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 preety straight , we can do 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— a date or a string.

We can use this to allow user to input Date Off between specified datetime, say between 08/05/08-08/20/08. So let’s drag range Validator next to 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 and so on) against another constant value or control.

Using this validator we can ask user to input age more 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;

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

Same we can do for re-password to compare with password, which should match it.

<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>

You can notice here 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 has to validate 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 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 concetrate 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 expression do not validate domain name

Let us try to invest more time here, we can also design more complex expression In addition to single characters, we can specify a class or a range of characters that can be matched in the expression. 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

Lets say we want to validate textbox ID to be multiple of 5, so for this we will create our own custom validator , one at client and other 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 all here, so finally we can write code for 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.”;

}

Cheers !

Advertisements

About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.

Discussion

4 thoughts on “Working with Input Validation Controls in ASP.NET 3.5

  1. Hi,
    I have bit confussion between client side validation and server side validation. In Asp.net we have multiple validatin control. So can you tell me these validation control are used for server side validation or client side validation.
    If these validation control are client side then how can we make server side or vice-versa.

    Posted by Pankhuri Sharma | 2011/03/08, 2:16 PM
    • Ideally, the validation of the user input should take place on the client side so that the user is
      immediately informed that there’s something wrong with the input before the form is posted back to
      the server. If this pattern is implemented correctly, it saves server resources and gives the user faster
      feedback. However, regardless of whether client-side validation is performed, the form’s data must
      also be validated on the server side. Otherwise, a shrewd attacker could hack the page by removing the
      client-side JavaScript that validates the input, saving the new page, and using it to submit bogus data.

      Writing validation code by hand is a lengthy task, especially because the models for client-side
      programming (typically JavaScript) and server-side programming (in this case, ASP.NET) are quite
      different. The developers at Microsoft are well aware of this, so, in addition to the set of HTML and
      web controls, they also developed a set of validation controls. These controls can be declared on
      a web form and then bound to any other input control. Once bound to an input control, the validation
      control performs automatic client-side and server-side validation. If the corresponding control
      is empty, doesn’t contain the correct data type, or doesn’t adhere to the specified rules, the validator
      will prevent the page from being posted back altogether.

      Hope this do some needful to you.
      Thanks

      Posted by iDunno | 2011/03/08, 2:22 PM
  2. Thanks for reply.
    I have one more question.
    It means when we bind Asp.net validation control to any control then at that time it does client side and server side both validation. But suppose I have to do only client side or server side validation then how this could be possible.

    Thanks.

    Posted by Pankhuri Sharma | 2011/03/08, 2:40 PM
  3. For client side validation , you can use client side programming : Javascript functions.
    For server side validation , you can use server side programming , ASP.NET , i.e. write code on submit button click , or textchange, or selectedindexchange events of control from code behind,

    Validation controls acts as an alternative for above two approaches.

    Posted by iDunno | 2011/03/08, 2:46 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow Vishalnayan on WordPress.com

Blog Stats

  • 211,463 hits
%d bloggers like this: