Tip

Limiting entry length in a textbox

This only works in R5/Win32 environments. Fields must have the property "Native OS Style" selected.

These scripts use Win32 API calls to change the window class attributes of the selected field and limit the number of characters the user can enter. The following example limits entries in a specific field to 25 characters.

If the user continues to type after 25 characters have been entered, he or she will hear an error beep. If the user tries to paste in text longer than 25 characters, he or she will be unable to do so.

Code in one field does NOT affect other fields on the form unless they also contain the "Entering" code. Different fields can have different limits.


[Form Globals]
Option Public
Const EM_LIMITTEXT = &HC5&
Declare Function GetFocus Lib "user32" () As Long
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (Byval hWnd As Long, Byval wMSg As Long, Byval wParam As Long, lParam As Long) As Long

Sub LimitText (wHandle As Long, MaxChars As Integer)
 Dim Result As Long
 If MaxChars > 0 Then
  Result = SendMessage(wHandle, EM_LIMITTEXT, MaxChars, 0)
 End If
End Sub

[Field Entering event]
Sub Entering(Source As Field)
 Dim hWnd As Long
 hWnd=GetFocus()
 Call LimitText(hWnd, 25)  ' Limits user to 25 chars max in this field
End Sub

This was first published in July 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.