Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Validation in ASP.NET

Posted by Ravi Varma Thumati on October 30, 2009

This article introduces the concept of Validation in ASP.NET and explores the many ways to do it with the controls Provided.                                                                                                                   

Article Contents:

  • Introduction
  • Required Fields
  • Using Regular Expressions
  • Comparing Values
  • Using Ranges
  • Custom Validation
  • Validation Summaries
  • Validation on the client side
  • Summary

Introduction

When you have a form that user’s submit data, its important that they don’t mess it up and enter weird stuff. Validation stops this but in ASP it was a tedious job of If statements to work out. I myself had a simple form that added users to a database, it had a heck of a lot of if statements. ASP.NET introduces – Validation Controls. These controls are just like Web Controls and can do many things like – Check if a field is filled out, Compare a field to something (or another), Use regular expressions on a field, Check to see if a field is within a certain range, you can even create your own!

Before we begin

Now, this is going to be a pretty big article/tutorial so lets get some of the common stuff out first.

Validation Controls only work for the following controls:

  • HTMLInputText
  • HTMLTextArea
  • HTMLSelect
  • HTMLInputFile
  • TextBox
  • ListBox
  • DropDownList
  • RadioButtonList

But what other controls could you use it on? Yes there are many more, but it’s rather hard to do everything in one. Next, the control syntax takes the form of –

<asp:ControlName runat=”Server” ControltoValidate=”ControlName” ErrorMessage=”MessageOtherProperties />

(Remember that the italics stuff is stuff that you change). Now it’s pretty obvious what ErrorMessage is (it’s the message that’s displayed if it turns out that the field isn’t valid). ControltoValidate is the id of the control that you’re going to be checking.

Required Fields

This is the big one that takes out those input statements! It checks to see if the ControltoValidate has some sort of value in it, if it does have something, then its IsValid property is set to True.

Enter your name (First & Last): <asp:TextBox runat=”server” /><br>

<asp:RequiredFieldValidator runat=”Server” ControltoValidate=”FName” ErrorMessage=”You didn’t fill in your name”/>

If the user doesn’t enter anything in the textbox, the message – “You didn’t fill in your name” appears in Red where the Validator is. You can put validators anywhere and the message just appears there.

Regular Expressions

I never really got the hang of regular expressions, but I can do some very simple things. Now if your putting all of my code into a file to test it, just add this one below the last. Remember that you aren’t limited to one validator per control, you can have as many as you like!

<asp:RegularExpressionValidator runat=”Server” ControltoValidate=”FName” ErrorMessage=”Your name isn’t in the correct format!” ValidationExpression=”\S+\s\S+” />

Now this checks to see weather the field matches the pattern in the ValidationExpression property, in this case the pattern in – “Any number of non-space characters, followed by one space, followed by any number of non-space characters”, this is the normal format for a name.

Comparing Data

This one compares data in one field to another field or to a constant (or a Data Type). It has several options which I will cover now.

  • Instead of ControltoCompare you can use ValuetoCompare if you want to use a constant value.
  • Operators can be one of the following:
    • DataTypeCheck
    • Equal
    • GreaterThan
    • GreaterThanEqual
    • LessThan
    • LessThanEqual
    • NotEqual
  • The Type property can be one of the following:
    • Currency
    • Date
    • Double
    • String
    • Integer

Here is the example:

First Name:<asp:textbox runat=”server” />Last Name: <asp:TextBox runat=”server” /><p>

<asp:CompareValidator runat=”Server” ControltoValidate=”FName2″ ControltoCompare=”LName2″ Operator=”NotEqual” ErrorMessage=”Your First Name can’t be your last name as well!” />

This makes sure that your first name isn’t your last name (don’t complain if your first name is also your last name, this is just an example!).

Ranges

This lets you see if a value is between two ranges. The range (set in MinimumValue and MaximumValue can either be a string or number). This checks to see if a zip code is within a specified range, I also used a Regular Expression Validator to check it too.

Please Enter your Zip Code:<asp:textbox runat=”server” /><p>

<asp:RangeValidator runat=”server” ControltoValidate=”ZIP” ErrorMessage=”Your Zip isn’t within the range (8000 – 9000)!” MinimumValue=”8000″ MaximumValue=”9000″ />

<asp:RegularExpressionValidator runat=”Server” ControltoValidate=”ZIP” ErrorMessage=”That Zip code is invalid (numbers only and 4 numbers long!)” ValidationExpression=”[0-9]{4}|[0-9]{5}” />

The RangeValidator made sure that you kept the value between 8000 and 9000, the regular expression one made sure that it was 4 or 5 (someone would complain if it was only 4) numbers long and only numbers.

Custom Validation

Creating your own validation isn’t too hard, if you’re no good a regular expressions then you can use this to do them. The following one makes sure that your entry is at least 8 letters long.

<script runat=”server”>
Sub ValidateMe(sender as object, e as ServerValidateEventArgs)
     If Len(e.Value) > 8 Then
          e.IsValid = True
     Else
          e.IsValid = False
     End If
End Sub
</script>

Enter a username:<asp:textbox runat=”server” /><p>

<asp:CustomValidator runat=”server” ControltoValidate=”username” ErrorMessage=”Username must be at least 8 letters long” />

Ok, the sub takes in the usual values, but it takes in ServerValidateEventArgs instead of EventArgs, this lets you get the value and set the IsValid Property. However this is server side validation (you’ll learn more about why this is important soon), to make it client side, just add the property – “OnClientSideValidator=”validating””. Then add some client side JavaScript to handle it (in the form of a function), otherwise it gets processed on the server.

There’s more!

More? Yes! Here are some things that will add you your adventures. Now obviously, having the Error text red all the time will get a bit annoying, so you can add the ForeColor = “Color” property to the control to change the error text color.

Now if you take all the code that I’ve given you on this page and put it into one file, add a submit button, form tags and then run it you will see that the Validation occurs with JavaScript and Span tags. This means that the page doesn’t get submitted until the validators are satisfied with what you’ve put in. But you’ll also see that there are gaps where the validators are on the page which are blank, they are activated when an error is found. You can set a Display property to change this –

  • Display = “None”    ‘No error message is displayed and the spaces are gone
  • Display = “Static”  ‘Default, spaces are left for the errors
  • Display = “Dynamic” ‘Spaces are generated only if an error occurs.

You’ll learn more about this in the next section.

When you submit the page, it doesn’t go through until the validators are happy, when it is submitted, its checked again and a value – Page.IsValid is generated to tell you if all the validators are happy –

<script runat=”server” >
Sub Page_Load(sender as object, e as EventArgs)
If Page.IsPostBack Then
    If Page.IsValid Then
       lblMessage.Text = “You passed Validation”
    End If
End If
End Sub
</script>

<asp:label runat=”server”/><p>

 

Validation Summaries

Now, if you want to take all the errors and put them in one place then you can with the ValidationSummary Control. This allows you to have a summary of all the errors. You can still have the in-line errors or you can turn them off by using the Display=none property. The following changes can be made to the script below:

  • DisplayMode can be – BulletList, List or SingleParagraph
  • ShowMessageBox can be – True. This shows a message box with the errors in them.

<asp:ValidationSummary DisplayMode=”BulletList” HeaderText=”The following errors were found on the page:” runat=”server” />

This just brings up a summary of the errors.

Validation on the client side

This is what you can do with validation in ASP.NET and as you can see you can do a lot.  The changes to the source are – some control’s Display is none so it only appears in the Summary. You will also notice that with the CustomValidator, the validation will occur on the server, so you get the message “Validation Passed” and then the error, to fix that, use Client-Side Java-Script, as you can see

………..

<Script>
  function validating( objSen, txtVal){
    var isvalid = True;
    if(txtVal.length < 8){
        isvalid = False;)}
    return isvalid
  }
</script>

Summary

Ok, that is Validation for you. It’s quite large, but I’m sure that you will use it.

Advertisements

One Response to “Validation in ASP.NET”

  1. Thanks for taking the time to debate this, I feel strongly about it and love studying extra on this topic. If possible, as you acquire experience, would you thoughts updating your blog with further info? It is extremely useful for me.

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

 
%d bloggers like this: