Improved Input Validation - Regular Joe
(Page 3 of 9 )
Let's take a look at some code that builds on the theory you learned on the previous page:
<%@ Page Language="C#" %>
<html>
<head>
<title>Registration Form</title>
<basefont face="Arial">
</head>
<body>
<div align="center">
<h1>User Registration Form</h1>
<form runat="server" method="POST" >
<asp:label id="lblUserName" runat="server" text="Username (at least eight alphabetic characters): " />
<asp:textbox id="strUserName" runat="server">
</asp:TextBox><br/>
<asp:RequiredFieldValidator id="strUserNameRFV" ControlToValidate="strUserName" ErrorMessage="Please enter a username!" runat="server" Display="dynamic" EnableClientScript="false"/>
<asp:RegularExpressionValidator id="strUserNameREV" runat="server" ControlToValidate="strUserName" ErrorMessage="Please enter at least eight alphabetic characters!" ValidationExpression="[a-zA-Z]{8,}"
display="dynamic" EnableClientScript="false"/><br/>
<asp:button id="Submit" Text="Submit" runat="server"/>
</form>
</div>
</body>
</html>
Once you have previewed this example in the browser, it's time to review the code. First, I have the mandatory <asp:textbox> and <asp:label> server controls to display the form field in the browser. Next, I have the RequiredFieldValidator control, which forces the user to enter a value in the associated server control. It is essential to have this validation control in my ASP.NET form, for reasons to be explained in the next few paragraphs.
This brings us to the RegularExpressionValidator validation control which, in addition to the standard "id", "ControlToValidate" and "ErrorMessage" attributes, also comes with a "ValidationExpression" attribute used to assign the regular expression to the validation control. Here, the value "[a-zA-Z]{8,}" is a regex that means "a string consisting of at least eight alphabetic characters".
The other two attributes, "Display" and "EnableClientScript", have been set so that the control is only displayed if there is an error and the validation takes place on the server.
Test the Control
Finally, it's time to explain the reason for using a RequiredFieldValidator control above. Try the following: remove this validation control and submit a blank entry. You will find that no error is reported because of a simple quirk - if there is no data in the text control, the RegularExpressionValidator control does not get activated at all. This quirk means that the end user could end up entering a blank value and the ASP.NET script will not complain at all.
Next: The Number Game >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire