Monday, March 26, 2012

MaxLength is not effective in TextBox

I have a multi-line text box and I set its max length to 50, I want to disallow continued typing when the maximum charactors is reached. But, I find it failed to do so. Any ideas why?

<asp:textbox id="txtNote" runat="server" Width="456px" TextMode="MultiLine" Height="56px" MaxLength="50" />Sorry, but the bad news is - - - that doesn't work for multi-line textboxes - - only for single-line textboxes - - you'd probably need to find a Javascript routine to handle that little chore
You can also use a regular expression validator to limit the size when the user tries to post or tab off the textarea. To actually stop the user from typing, you'd have to handle the keypress event with javascript on the browser.
Today my friend is your luck day ;)

Sorry it took me so long to get back to you. It took me a few to write this :)

Simply make an instance of the class below and set the MaxLength Property.


Imports System.Web.UI.WebControls.BaseValidator
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text

Public Class MPIMaxLengthValidator : Inherits BaseValidator

Dim intMaxLength As Integer
Dim blnRestrictLength As Boolean

'The max length is set as a property
Public Property MaxLength() As Integer
Get
MaxLength = intMaxLength
End Get
Set(ByVal Value As Integer)
intMaxLength = Value
End Set
End Property

Public Property RestrictLength() As Boolean
Get
RestrictLength = blnRestrictLength
End Get
Set(ByVal Value As Boolean)
blnRestrictLength = Value
End Set
End Property

'Here we are overriding the EvaluateISValid function of the BaseValidator
'Basically this takes care of the server side validation. It contains
'the logic to determine whether or not the user has passed validation in
'this case it involves ensuring that one of the length of the text is less
'than that what is allowed
Protected Overrides Function EvaluateIsValid() As Boolean
If Me.ControlToValidate.Length > MaxLength Then
Return True
Else
Return False
End If
End Function

'This will add the javascript validtion on the prerender. It first ensure the client
'has a javascript enabled browser
Protected Overrides Sub onPreRender(ByVal E As EventArgs)
If EnableClientScript = True Then
Me.ClientScript()
End If
MyBase.OnPreRender(E)
End Sub

'This is the client side script. It is registered as clientside code called "MPIMaxLengthValidator"
'& the ID that we have given the validator. A string builder is used to create all the
'javascript and then it is registered using the registerClientSideScriptBlock method.
Protected Sub ClientScript()

Me.Attributes("evaluationfunction") = "MPIMaxLengthValidator" & Me.ID

Dim sbScript As New StringBuilder()
sbScript.Remove(0, sbScript.Length)

sbScript.Append("<script language=""javascript"">")
sbScript.Append("function MPIMaxLengthValidator" & Me.ID & "() {")

Dim txtBox As New TextBox()
txtBox = FindControl(Me.ControlToValidate)

Dim strID As String
strID = txtBox.ID

sbScript.Append("if (document.getElementById('" & strID & "').value.length >" & MaxLength & "){")
sbScript.Append("return false;")
sbScript.Append("} else {")

sbScript.Append("return true;")
sbScript.Append("}")
sbScript.Append("}")
sbScript.Append("</script>")
Me.Page.RegisterClientScriptBlock("MLENScript" & Me.ID, sbScript.ToString())

If RestrictLength = True Then
txtBox.Attributes("onKeyPress") = "CheckLength" & Me.ID

Dim sbRestict As New StringBuilder()
sbRestict.Append("<script language=""javascript"">")

sbRestict.Append("function CheckLength" & Me.ID & "() {")

sbRestict.Append("if (window.event.srcElement.value.length >=" & MaxLength & ") {")
sbRestict.Append("return false;")
sbRestict.Append("}")

sbRestict.Append("}")
sbRestict.Append("</script>")
Me.Page.RegisterClientScriptBlock("CheckLength" & Me.ID, sbRestict.ToString())

End If

End Sub

End Class

Any questions... post away...

AspDotNetGuy
Hi,

Well once the user reaches 50 characters why not make the TextBox enable property to false so the user cannot input any data.
I have my doubts on setting TextBox enable property to false because a user would not be able to edit his/her entry, yar?
hi,

how about using Range validator and when the count is greater then 50 prints the message that " Your text is illegal " and assign Page.IsValid = false;
Range Validator is not working even though I set Type=String, and Max value is set to be 50. It always display error message when it is time to validate. Do not know why, it is supposed to work based on MSDN.

I actually want to stop user from typing when maximum reached. This exactly happens in WinForm multiline TextBox. I just hope Microsoft would fix this control in ASP.NET 2.0.

Hi, AspDotNetGuy, thank you for spend really some time coding your validator for this post. So, basically it is still a valiator and can not stop continuted typing. I will have to turn to it if this is the last resort.

Thank you all.
Sorry I didn't realize you were trying to stop continued typing. You can do this with Javascript.

Pseuso:
Count the characters on keypress
If characters > 50
Capture keyevent and return false

Would this do it for you?

If you need help with the code, let me know.

Thank you,

AspDotNetGuy
Check outValidating MaxLength of the TextArea using CustomValidator

Hi, AspDotNetGuy

If it is quick and easy for you to write the code you suggested, I would be appreaciated to see the working code.
How would you use a regular expression validator to limit the size of input? I'm actually having the same problem as the initial post; although I do not need to stop the typing when the user makes an input over the maximum length. I just need a simple validator that says you have inputted more than the maximum allowed. And I would rather refrain from the usage of Java script because wouldn't it be different (style wise) from the other validators that I currently have? Any assistance would be appreciated!

No comments:

Post a Comment