Click here to Skip to main content
15,885,004 members
Articles / Web Development / ASP.NET

Length Validation for all Multiline Textboxes on a Page

Rate me:
Please Sign up or sign in to vote.
4.07/5 (8 votes)
30 Dec 2007CPOL 54.4K   231   23   12
How to enable length validation for all Multiline textboxes on a page using a line of code...

Sample Image - MultilineLengthValidator.jpg

Introduction

It is commonly known that the MaxLength attribute does not work for textboxes with the TextMode property set to MultiLine since they are rendered as <textarea> HTML controls, which miss this property.

There are lots of great articles around to solve this, but using custom controls etc., is too time expensive for larger projects.

This approach iterates through all the controls in a page (or other container controls) and attaches a JavaScript to all multiline textboxes to enable length validation. It works with AJAX / ATLAS, FormViews, and all commonly known browsers.

How to use

Add multiline textboxes to your page by setting the MaxLength property. Now, all you have to do is use one line of code...

For performing length validation on all multiline textboxes on a page:

Put TextAreaValidator.CheckMaxLength(this); inside the page's Page_Load function.

For performing length validation on a specific textbox:

Put TextAreaValidator.CheckMaxLength(theTextBox); inside the page's Page_Load function.

For FormViews (also inside ATLAS UpdatePanels), use the FormView's OnItemCreated event with:

TextAreaValidator.CheckAllMaxLengthsWithinParentControl((FormView)sender), since the container controls are created at runtime and previously inaccessible.

Enjoy...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Austria Austria
Sina Falahati is a Medical student at Vienna Medical University and also student at Technical University of Vienna.

His preferred languages are Music, C++, C#, Turbo Pascal / Delphi, XML, German and Persian.

Comments and Discussions

 
GeneralInvalid Character when run the EncloseScriptBlock Pin
Member 190150028-Apr-11 9:46
Member 190150028-Apr-11 9:46 
GeneralExcellent - Small update Pin
0x29A31-Mar-09 7:59
0x29A31-Mar-09 7:59 
GeneralGood Job! Pin
edusabrz23-Feb-09 12:31
edusabrz23-Feb-09 12:31 
GeneralVB.net version of this code Pin
dolphinpointe10-Sep-08 12:04
dolphinpointe10-Sep-08 12:04 
GeneralRe: VB.net version of this code [modified] Pin
dolphinpointe10-Sep-08 13:48
dolphinpointe10-Sep-08 13:48 
GeneralRe: VB.net version of this code (Working) Pin
DidiKunz7-Aug-12 6:22
DidiKunz7-Aug-12 6:22 
corrected VB version:

VB
Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

' Created by Sina Falahati on 29.10.2006 07:39
' With thanks to:
' Abaif for his JSHelper CheckTextAreaMaxLength sample
' A. Kluge for his Textarea-Counter
' http://www.codeproject.com/KB/aspnet/MultilineLengthValidator.aspx?msg=2718271#xx2718271xx

'/ <summary>
'/ Description:
'/ If you specify TextMode="SingleLine" on a TextBox, it generates an html <input> box with a
'/ MaxLength attribute. If you specify TextMode="MultiLine", it generates an html <textarea>
'/ box ... and doesn't set the MaxLength attribute, since it's undefined for <textarea> elements.
'/ This will add a check onKeyUp for the textarea that will prevent too many
'/ characters from being entered. Set the MaxLength as normal as a property of the TextBox and then call
'/ this method to generate JavaScript to do the client-side checks.
'/
'/ How to use:
'/ For performing length validation on all multiline Text-Boxes on a page: Put "CheckAllMaxLengthsWithinParentControl(this);" inside the page's Page_Load function
'/ For performing length validation on a specific Text-Box: Put "CheckMaxLength(theTextBox);" inside the page's Page_Load function
'/ For FormViews inside ATLAS Update-Panels use FormView's OnItemCreated event with CheckAllMaxLengthsWithinParentControl((FormView)sender);
'/ </summary>
' Converted to vb.net (but no tested) by Jim Engebretson

Public Class TextAreaValidator

  Public Shared Sub CheckAllMaxLengthsWithinParentControl(ByVal oParent As System.Web.UI.Control)

	 Dim oChild As Control = Nothing
	 Dim oChildTextBox As TextBox = Nothing

	 If ((oParent Is Nothing) Or (Not oParent.HasControls())) Then
		Return
	 End If

	 Dim iItem As Integer
	 For iItem = 0 To oParent.Controls.Count - 1 Step iItem + 1
		oChild = oParent.Controls(iItem)
		If (Not oChild.Visible) Then
		   Continue For
		End If

		If (oChild.Controls.Count > 0) Then
		   CheckAllMaxLengthsWithinParentControl(oChild) ' iterate through child-controls
		   If oChild.GetType.ToString = "System.Web.UI.WebControls.TextBox" Then
			  ' If (ct = System.Web.UI.WebControls.TextBox) Then
			  oChildTextBox = CType(oChild, TextBox)
			  ' Change TextBox Properties Here
			  ' only Multiline Text-Boxes need this
			  If (oChildTextBox.TextMode = TextBoxMode.MultiLine And oChildTextBox.MaxLength <> 0) Then ' 0 == no limit
				 CheckMaxLength(oChildTextBox)
			  End If
		   End If
		End If
	 Next
  End Sub

  Public Shared Sub CheckMaxLength(ByVal textArea As System.Web.UI.WebControls.TextBox)
	 textArea.Attributes.Add("onKeyUp", _
	 "CheckMaxLength(event," & _
	 "'" & textArea.ClientID & "'," & _
	 textArea.MaxLength & ");")

	 textArea.Attributes.Add("onChange", _
	 "CheckMaxLength(event," & _
	 "'" & textArea.ClientID & "'," & _
	 textArea.MaxLength & ");")

	 RegisterCheckMaxLength(textArea.Page)
  End Sub

  Private Shared Sub RegisterCheckMaxLength(ByRef page)
	 Dim script As String = String.Empty

	 'Build the function block
	 script = "function CheckMaxLength(e, textarea_id, max) {" & vbCrLf
	 script += "var theTextArea = document.getElementById(textarea_id);" & vbCrLf
	 script += "if (!e.which) keyCode = event.keyCode; // ie5+ op5+" & vbCrLf
	 script += "else keyCode = e.which; // nn6+" & vbCrLf
	 script += "if (theTextArea.value.length>max)" & vbCrLf
	 script += "{" & vbCrLf
	 script += "theTextArea.value = theTextArea.value.substring(0,max); " & vbCrLf
	 script += "}" & vbCrLf
	 script += "};" & vbCrLf

	 'Enclose function <script> tags and register at top of page
	 'Check whether they are already registered
	 If (Not page.IsClientScriptBlockRegistered("CheckMaxLength")) Then
		'Register the script
		page.RegisterClientScriptBlock("CheckMaxLength", EncloseScriptBlock(script))
	 End If
  End Sub


  Private Shared Function EncloseScriptBlock(ByVal script) As String
	 script = "<script type='text/javascript'>" & vbCrLf & _
	 "<!--" & vbCrLf & _
	 script & vbCrLf & _
	 "// -->" & vbCrLf & _
	 "</script>"
	 Return script
  End Function

End Class

GeneralThanks Pin
Sam.M22-Jan-07 17:59
Sam.M22-Jan-07 17:59 
GeneralError Pin
mishenkovks8-Nov-06 21:30
mishenkovks8-Nov-06 21:30 
AnswerRe: Solved Pin
Sina Falahati9-Nov-06 8:29
Sina Falahati9-Nov-06 8:29 
GeneralThank you Pin
mishenkovks8-Nov-06 3:32
mishenkovks8-Nov-06 3:32 
Generalnice job Pin
Majid Shahabfar7-Nov-06 1:29
Majid Shahabfar7-Nov-06 1:29 
GeneralRe: nice job Pin
Sina Falahati9-Nov-06 8:30
Sina Falahati9-Nov-06 8:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.