Form Validation with ASP.NET - It Doesn't Get Any Easier!, Part 4
Read Part 1
Read Part 2
Read Part 3
In Part 3 we looked at adding two
validators. In this fourth and final part we'll look at adding a single
validator and tie up all the loose ends!
Time to add our last validator control, the
RangeValidator, to ensure that the Age is between a valid
range (we don't want someone entering an age of 2 or 739, which would pass our
control). For this example, we'll allow ages between 5 and 120. The
RangeValidator has the following
Type="Comparison Data Type"
ErrorMessage="Message to display for invalid data..."
MinimumControl need to reference
with the maximum and minimum ranges entered.
Let's go ahead and add the
RangeValidator to each form field. The validator
should go right next to the form field textbox, like so:
<!--Age textbox and validation-->
<asp:TextBox id="minAge" text="5" runat="server" visible="False" />
<asp:TextBox id="maxAge" text="120" runat="server" visible="False" />
<input type="text" id="txtAge" runat="server"/>
ErrorMessage = "You must provide your age!"
ErrorMessage = "Your age must be one to three digits."
<asp:RangeValidator runat="server" Type="Integer"
ErrorMessage = "Your age must be between 5 and 120."
Note the two
asp:TextBox controls we added up at the top. Their
Visible property is set
False so they won't show up on the Web page, but they are needed for the
to function properly. Note that we have hard coded the values of 5 and 120 into the
Now that we have all of our validator controls in place, all that's left is the code to successfully handle the form
if every form field is deemed valid. As you saw in our first code snippet, the submit button for the form is
created with an
asp:button. We need to create the
btnSubmit_OnClick function, which we
can do with the following server-side script block:
<SCRIPT LANGUAGE="VB" RUNAT="SERVER">
Sub btnSubmit_OnClick(Obj as Object, E as EventArgs)
'Determine if the form entries were valid
If Page.IsValid then
'This is the point where we want to handle the form.
'Once we've "handled" the form we'll redirect the user to
'the ThankYou.aspx page.
'You could do a number of things here, to "handle" the form.
'Perhaps you want to send an email to someone, or update/insert a
'record in a database. In any case, this is the place where you would
Page.Navigate("ThankYou.aspx?Name=" & txtName.Text) 'Redirect the user
Well, that's about it! While a lot of the code may be very new to you if you've not worked with ASP.NET before,
hopefully it has gotten your feet wet and shown you how easy form validation is with ASP.NET!
Attachments:View the source for
Validation.aspx in text format
Read the official docs on the Validator Controls
Visit the ASP.NET Article Index
Visit the Regular Expressions Article Index