Ketone Cops

February 6, 2008

Monitor mandatory text fields in ASP.NET 2.0

Filed under: ASP.NET 2.0 — delroger @ 1:19 pm
Tags: , ,

I wanted to create an easy way to programmatically monitor textfields in a webpage form and highlight them if they were empty, not to force input or disallow saves and updates, but just to highlight for the website user that the field needed to be filled in eventually.

First, an acknowledgement: I’d been using the ‘ClientSidePage’ method for checking ‘dirty’ data from here and decided to use similar techniques.

The ClientSidePage inherits from the System.Web.UI.Page base class; your webpages then need to inherit from the ClientSidePage class.

The class has two protected strings, which set the colours for highlighting textfields or reverting to the normal background colour. In this case, I’m using a lovely pinkish colour for highlighting, reverting to white if text is entered in the textbox.

Protected HighlightedColour As String = "#f8e0e0"
Protected NormalColour As String = "white"

The class contains a Public Sub called WatchForEmpties that takes a web control as a parameter and adds attributes for onkeyup and onfocus. Both onkeyup and onfocus invoke a javascript called HighlightIfEmpty, which passes the control as a parameter.

The control is added to an array of all the controls on the page that are being monitored. Finally, javascripts are registered for highlighting the empty textboxes and for setting the initial colours for all textboxes that are part of the array of controls.

The class file now looks like this:

Imports Microsoft.VisualBasic

Public Class MonitoringPage
Inherits System.Web.UI.Page
Protected HighlightedColour As String = "#f8e0e0"
Protected NormalColour As String = "white"

Public Sub WatchForEmpties(ByVal wc As WebControl)
  If wc Is Nothing Then Exit Sub
  Dim strFocus As String = wc.Attributes("onfocus")
  If Not strFocus Is Nothing Then
    wc.Attributes("onfocus") = strFocus & "HighlightIfEmpty(this);"
  Else
    wc.Attributes("onfocus") = "javascript:HighlightIfEmpty(this);"
  End If
  Dim strKeyup As String = wc.Attributes("onkeyup")
  If Not strKeyup Is Nothing Then
    wc.Attributes("onkeyup") = strKeyup & "HighlightIfEmpty(this);"
  Else
    wc.Attributes("onkeyup") = "javascript:HighlightIfEmpty(this);"
  End If
  Page.ClientScript.RegisterArrayDeclaration("WatchForEmptiesIDs", """" & wc.ClientID & """")
  WatchForEmptiesOnPageLoad()
End Sub

Private Sub WatchForEmptiesOnPageLoad()
  If Not Page.ClientScript.IsStartupScriptRegistered("HighlightIfEmptyScript") Then
  Dim t As Type
  t = Me.GetType()
  Page.ClientScript.RegisterStartupScript(t, "HighlightIfEmptyScript", _
  "<script language=""JavaScript"">" & Environment.NewLine & _
  " HighlightIfEmpty(Object);" & Environment.NewLine & _
  "</script>")

  Page.ClientScript.RegisterClientScriptBlock(t, "HighlightIfEmptyFunction", _
  "<script language=""JavaScript""">" & Environment.NewLine & _
  " function HighlightIfEmpty(Object) " & Environment.NewLine & _
  "   { " & Environment.NewLine & _
  "     if (Object) " & Environment.NewLine & _
  "     { " & Environment.NewLine & _
  "       var re = /\s/g; " & Environment.NewLine & _
  "       RegExp.multiline = true; " & Environment.NewLine & _
  "       var str;" & Environment.NewLine & _
  "       if (Object.value == null) " & Environment.NewLine & _
  "       { " & Environment.NewLine & _
  "       } " & Environment.NewLine & _
  "       else " & Environment.NewLine & _
  "       { " & Environment.NewLine & _
  "         if (Object.value.length > 0) " & Environment.NewLine & _
  "         { " & Environment.NewLine & _
  "           str = Object.value.replace(re, '');" & Environment.NewLine & _
  "         } " & Environment.NewLine & _
  "         else " & Environment.NewLine & _
  "         { " & Environment.NewLine & _
  "           str = '';" & Environment.NewLine & _
  "         } " & Environment.NewLine & _
  "         if (str.length > 0) " & Environment.NewLine & _
  "         { " & Environment.NewLine & _
  "           return Object.style.backgroundColor = '" & NormalColour & "'; " & Environment.NewLine & _
  "         } " & Environment.NewLine & _
  "         else " & Environment.NewLine & _
  "         { " & Environment.NewLine & _
  "           return Object.style.backgroundColor = '" & HighlightedColour & "'; " & Environment.NewLine & _
  "         } " & Environment.NewLine & _
  "       } " & Environment.NewLine & _
  "     } " & Environment.NewLine & _
  "   } " & Environment.NewLine & _
  "</script>")
  End If

  If Not Page.ClientScript.IsStartupScriptRegistered("WatchForEmptiesAssignment") Then
    Dim t As Type
    t = Me.GetType() '? typeOf(Page)
    Page.ClientScript.RegisterStartupScript(t, "WatchForEmptiesAssignment", _
    "  <script language=""JavaScript"">" & Environment.NewLine & _
    "   SetColoursForEmptyBoxes();" & Environment.NewLine & _
    "  </script>")

    Page.ClientScript.RegisterClientScriptBlock(t, "WatchForEmptiesAssignmentFunction", _
    "  <script language=""JavaScript"">" & Environment.NewLine & _
    "   function SetColoursForEmptyBoxes() { " & Environment.NewLine & _
    "     for (var i = 0; i < WatchForEmptiesIDs.length; i++) {" & Environment.NewLine & _
    "     var elem = document.getElementById(WatchForEmptiesIDs[i]);" & Environment.NewLine & _
    "     HighlightIfEmpty(elem); " & Environment.NewLine & _
    "     }" & Environment.NewLine & _
    "   }" & Environment.NewLine & _
    "</script>")
  End If
End Sub

End Class

If you want to use the monitoring functions in your webpages, they need to inherit this class rather than System.Web.UI.Page

So, in your code-behind page, instead of:

Partial Class Default
  Inherits System.Web.UI.Page
...
End Class

you should have:

Partial Class Default
  Inherits MonitoringPage
...
End Class

To then monitor a textbox that needs to have input, you just need to have a page prerender sub that calls WatchForEmpties, passing in the name of the textbox, like this:

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
  WatchForEmpties(Me.Textbox1)
End Sub

When the box has an empty string or no text, it will be highlighted. If any text is present, the box will revert back to a white background.

Advertisements

1 Comment »

  1. You may add a method to ByPassingControl(WebControl) so that some controls are ignored for highlight.

    Comment by David — June 12, 2008 @ 5:55 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: