ASP.NET offers a full suite of validation controls, which can be used to easily validate user input in other ASP.NET controls. These include the RequiredFieldValidator , CompareValidator , RangeValidator , RegularExpressionValidator , CustomValidator , and ValidationSummary controls. This section talks about and shows how to use the RequiredFieldValidator and the RegularExpressionValidator . Although these are covered in depth in Chapter 12, I'll talk about them here in the context of ASP.NET server controls. Examples showing how to use the others can be found on www.UsingASP.net. Imagine that you have a TextBox control in your code as follows : <asp:TextBox id="TextBox1" runat="server" /> If you have a required field and you want to indicate to the user that the field isn't filled out (this might be with some sort of visual such as an asterisk), all you need to do is add a RequiredFieldValidator as follows: <asp:RequiredFieldValidator id="RequiredFieldValidator1" ControlToValidate="TextBox1" Display="Static" Width="100%" runat="server" > * </asp:RequiredFieldValidator> The ControlToValidate attribute determines which control is monitored by this control. Note that the text that is output when the monitored control ( TextBox1 ) isn't filled out is, by default, an asterisk. However, this can be any text of your choice. The following code is a complete example; Figure 6.14 shows it executing: Figure 6.14. The RequiredFieldValidator makes it easy to require fields.
<form runat="server"> <table> <tr width="100%"> <td width="75%"> Please enter your name: <asp:TextBox id="TextBox1" runat="server" /> </td> <td width=25%> <asp:RequiredFieldValidator id="RequiredFieldValidator1" ControlToValidate="TextBox1" Display="Static" Width="100%" runat="server" > * </asp:RequiredFieldValidator> </td> </tr> </table> </form> Regular expressions are used on the Web frequently to enable users to input different types of data. The RegularExpressionValidator can make sure the data is what you expect before your application has to do any processing on it. This can save your middle and database tiers from unnecessary processing if users enter faulty data. The following example enables users to input a five-digit numeric zip code. It validates the input and alerts users to a problem, as shown in Figure 6.15. Figure 6.15. The RegularExpressionValidator flags users to problems.
<center> <table border=1 width=100%> <tr> <td><b>Example</b></td> <td><b>Source Code</b></td> </tr> <tr> <td> <center> <form runat="server"> <table> <tr> <td width="50%"> Enter a five digit zip code: <asp:TextBox id="TextBox1" runat="server" /> </td> <td width="50%"> <asp:RegularExpressionValidator id="REV1" runat="server" ControlToValidate="TextBox1" ValidationExpression="^\d(5)$" Display="Static" > Zip code must be 5 numeric digits. </asp:RegularExpressionValidator> </td> </tr> </table> </form> </center> |