Input Validation With ASP.NET, Part 1 - First Glance
(Page 3 of 6 )
Enough with the theory, already; let's get our hands dirty with some code, shall we?
<%@ Page Language="C#" %>
<html>
<head>
<title>What's In A Name?</title>
<basefont face="Arial">
</head>
<body>
<form runat="server" method="POST" >
<asp:label id="lblFirstName" runat="server" text="Your name, please? " />
<asp:textbox id="strFirstName" runat="server"/>
<br />
<asp:RequiredFieldValidator id="strFirstNameRFV"
ControlToValidate="strFirstName" ErrorMessage="Don't you have a name?"
runat="server"/>
<br />
<asp:button id="Submit" Text="Submit" runat="server"/>
</form>
</body>
</html>
In case you see errors about a missing "WebUIValidation.js" file instead of the form above, ensure that this file is under your Web server root, in the "\aspnet_client\system_web\1_1_4322" folder (you can locate the file by doing a quick search on your .NET development system), and then try again.
Now, submit the form without entering any data, and you should now see an error message on the screen.
There's nothing very exciting about the code above; the first few lines simply make use of two plain-vanilla server controls, a label and a textbox; the latter allows the user to enter his/her name. The meat of the script lies in this line:
<asp:RequiredFieldValidator id="strFirstNameRFV"
ControlToValidate="strFirstName" ErrorMessage="Don't you have a name?"
runat="server"/>
This is your very first ASP.NET Validator control. Aptly called the RequiredFieldValidator control, it forces the user to enter a value in the associated field. Here are the attributes I've used:
- The id attribute specifies a unique identifier for this control (useful if you want to script actions based on the state of this object).
- The ControlToValidate attribute associates this control with a form field. Since I want to validate the "strFirstName" textbox control, I've assigned it this value.
- The ErrorMessage attribute stores the message to be displayed to the user, if she does not enter a value in the "strFirstName" textbox control.
- The mandatory runat=server attribute tells the .NET CLR that this control has to be processed at the server and not the client.
Now, you might be wondering whether the client or the server performed the validation. If you guessed the client, then you guessed right! Note that this doesn't mean that server-side validation is disabled; if, for some reason, client-side validation fails, the server will leap in and enforce your validations instead.
Next: If Looks Could Kill >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire