ASP.NET HowTo: including default text in a Textbox while enforcing server-side validation
I was asked recently to develop a process wherein a server-side TextBox control could have some default text included in it, which seems to be more and more the reliable UI model for ensuring people fill out required form fields. The kicker is that the app in which it runs still needs to enforce server-side validation, meaning that the TextBox would need input data other than the said default value, and not have the default text erroneously have the form be seen as valid.
This is quite easy to do if done all on the server, however doing so usually requires handling the OnTextChanged event, which forces a server roundtrip which is largely unnecessary. The code below displays a single TextBox control, with the given value "(enter something here)". Note how the ONFOCUS and ONBLUR events are handled on the client in JavaScript routines for cases when the TextBox becomes the active or inactive form element, respectively. I add these client-side event handlers to the server-side TextBox control in the Page_Load event by adding items to the Attributes collection.
Upon gaining focus, the TextBox clears out its default value, and when losing focus (if no new value has been entered), re-inputs the default text. The magic is in the server-side RequiredFieldValidator control that validates the TextBox, specifically in the InitialValue property. If the value of the TextBox is something other than the default value (and not left blank), the form will be considered valid and be submitted. If not, the form will preserve the validation rule.
It's a simple, gimmicky, but nonetheless effective way of providing a better user experience.
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender,EventArgs e)
{
// handle the client-side ONFOCUS and ONBLUR events
txtName.Attributes.Add("onfocus","clearText()");
txtName.Attributes.Add("onblur","resetText()");
}
private void DisplayText(object sender,EventArgs e)
{
Response.Write("You entered the following text: <b>" + txtName.Text.Trim() + "</b>");
}
</script>
<html>
<head>
<title>Alterting control focus on the server side</title>
<script language="JavaScript">
<!--
function clearText() {
document.form1.txtName.value = ""
}
function resetText() {
if(document.form1.txtName.value == "")
document.form1.txtName.value = "(enter something here)"
}
// -->
</script>
</head>
<body>
<form runat="server" id="form1">
This is the textbox into which you'll enter data:
<br/>
<asp:Textbox id="txtName" text="(enter something here)" runat="server"/>
<br/>
<asp:RequiredFieldValidator id="requireName" controltovalidate="txtName" runat="server" display="dynamic" initialvalue="(enter something here)" errormessage="* Required"/>
<br/><br/>
<asp:Button id="btnSubmit" onclick="DisplayText" text="Click here to submit!" runat="server"/>
</form>
</body>
</html>