Web Design that taps into the haromny and vision of your dreams.

Validating Input using ASP.Net

Validating Input in C#

Written By on in C#

1,232 words, estimated reading time 6 minutes.

Validation of data is vital when capturing information from a user. Validation can be as simple as checking that a field has been filled in or more completed such as range checking and format checking.

Active Server Pages (ASP.Net) Series
  1. What is ASP.Net?
  2. ASP.Net for PHP Developers
  3. Creating a Simple ASP.Net Page
  4. ASP.Net Website Navigation Using a SiteMap
  5. Using ASP.Net Master Pages and Content Pages
  6. Validating Input using ASP.Net
  7. Tracing and Remote Debug in ASP.Net
  8. Creating Custom Error Pages with ASP.Net
  9. Managing Session State in ASP.Net
  10. Using Themes and Skins in ASP.Net
  11. Creating User Controls in ASP.Net
  12. Difference between ASP.Net User and Custom Server Controls
  13. Creating Fully Themable Websites with ASP.Net
  14. Ultimate Guide to the Web.Config File
  15. Adding StyleSheets to ASP.Net via C#
  16. Extending the Web Sitemap Xml Document

The .Net platform provides a set of components for form validation that can be found in the Validation section of the toolbox.

We are going to start off with a basic form that asks for a name and a telephone number. It's a simple form, but we are not going to any design awards here!

<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
 
 
<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>
 
 
 
 
<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

When you build and run the application you will notice that you can submit the form without any information entered and you can also submit the form with numbers in the name field and vice versa. This will clearly result in useless data.

Required Field Validator

The simplest form of validation is to make a field a required field. This will ensure that the specified field contains some data, although it may not be valid data. The RequiredFieldValidator can be dragged onto a form, one for each control to be validated.

<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a name." ControlToValidate="txtName"></asp:RequiredFieldValidator>
 
 
<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter a number." ControlToValidate="txtTelephone" ></asp:RequiredFieldValidator>
 
 
 
 
<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

Now when you run the application you will not be able to submit the form unless both text boxes contain data. While this may serve most purposes, we can go one further and require that the name field can only contain letters, spaces and hyphens and that the telephone number field only contains numbers. We can do this using a RegularExpressionValidator.

Regular Expression Validator

This is a more advanced validator and it allows a form to be submitted if the contents of the control match a regular expression. This allows for a wide range of validation rules to be used including checking the correct format of credit card numbers, social security numbers, telephone numbers and even a product or style code.

A Regular Expression Validator will be in addition to any Required Field Validator assigned to the control. You must set the ControlToValidate and ErrorMessage property as before, however, you must also specify a ValidationExpression string that contains a valid regex.

<asp:Label ID="lblName" runat="server" Style="position: relative" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtName">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtName" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please only enter letters, spaces and hyphens" ValidationExpression="^[a-zA-Z -]*$"></asp:RegularExpressionValidator>
 
 
<asp:Label ID="lblTelephone" runat="server" Style="position: relative" Text="Telephone:"></asp:Label>
<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtTelephone">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtTelephone" ID="RegularExpressionValidator2" runat="server" ErrorMessage="Please only enter numbers (0-9)" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
 
 
 
 
<asp:Button ID="btnSubmit" runat="server" Style="position: relative" Text="Submit" />

Limit Number of Characters

Sometimes it may be required to validate the length of a string or number, for example, you may only want a four-digit number to be entered. You can do this from within the regular expression.

<asp:RegularExpressionValidator ControlToValidate="txtTelephone" ID="RegularExpressionValidator2" runat="server" ErrorMessage="Please only enter numbers (0-9)" ValidationExpression="^[0-9]{4}$"></asp:RegularExpressionValidator>

In this example, the addition of {4} will limit the number of characters entered to four. If less than four or more than four are entered then the error message will be displayed.

Using Multiple Validators

You can use multiple validation objects on a control, just add them to the form, set them up and assign the ControlToValidate property. One thing you will notice is the position of the controls relative to the position on the form.

Validating Input using ASP.Net
Validating Input using ASP.Net

The controls appear at runtime in the same position that they were in design time. This may be an undesired position as it is visually more impressive if a validation text is located next to the box in question. You can force all validators to appear in the same location by setting the display property from Static to Dynamic.

Validating Input using ASP.Net
Validating Input using ASP.Net

Page Validation

The Page object accessible from the C# code behind has a property called IsValid which can be used to determine if there are validation errors on the page. IsValid contains the combined result of all the validators on the page.

if (Page.IsValid)
{
  Message.Text = "Page is Valid";
}

Validation Summary

A validation summary object can be used to provide a list of fields that are in error. As well as setting the ErrorMessage of the validator to the customer friendly message (i.e. "Name cannot be left blank.") we also need to set the Text property to identify the control in error, most commonly an asterisk is used.

<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="The following errors were found:" />
Name:
 
<asp:TextBox ID="TextBox2" runat="server" Style="left: 0px; position: relative"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Name cannot be blank." Style="position: relative">*</asp:RequiredFieldValidator>
 
 

The ValidationSummary object will only be shown when a control is in an error state.

Validating Input using ASP.Net
Validating Input using ASP.Net

Last updated on: Friday 23rd June 2017

 

Comments
satish

satish

Very nice tutorial, I liked it... It accepts characters and digits.. which are most important.

Thank you

Reply to satish

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me