Input Validation With ASP.NET, Part 1 - If Looks Could Kill
(Page 4 of 6 )
In the previous example, I allowed the client to carry out input validation first. However, at times, you may want to shift this responsibility directly to the server. ASP.NET allows you to do this, simply by adding an additional attribute to your RequiredFieldValidator definition.
<%@ 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"/>
<asp:RequiredFieldValidator id="strFirstNameRFV"
ControlToValidate="strFirstName" ErrorMessage="Don't you have a name?"
runat="server" EnableClientScript="false" ForeColor="#FF0000"
BackColor="#CCCCCC" BorderWidth="2" BorderColor="#000000" Display="dynamic"
Style="font-family:verdana;padding: 3px;font-weight:bold;font-size:10px" />
<asp:button id="Submit" Text="Submit" runat="server"/>
</form>
</body>
</html>
I'm sure you're wondering why the number of attributes for the RequiredFieldValidator control has suddenly increased. A close inspection will reveal that most of these are responsible for the formatting of the error message. However, the first and most important change is the "EnableClientScript" attribute, a simple flag that can be set to "true" or "false", depending on whether or not you wish to carry out client-side validation. Set this to "true" (the default value) and all validations will be carried out on the client; set it to "false" and the server will take over the responsibility for input validation
Next, we have the "Display" attribute. This is an interesting attribute, useful if you want to ensure that the error messages generated by the Validator do not destroy the design and layout of your Web pages. If this value is set to "dynamic", the area where the error message appears is hidden till such time as the error message is to be displayed
Finally, I have a list of attributes to control the display of the error message:
- The ForeColor attribute controls the color used to display the error message.
- The BackColor attribute controls the background color for the area displaying the error message.
- The BorderWidth attribute controls the width of the border for the area displaying the message.
- The BorderColor attribute controls the color of the border around the message.
- The Style attribute allows you to specify CSS properties for the text of the error message.
Next: Pizza Power >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire