How to limit a textbox input strlength

Cableguy

Expert
Licensed User
Longtime User
You can use my password textbox library, wich can be used as a normal textbox with a few extras....
Check the samples and tis
 

agraham

Expert
Licensed User
Longtime User
This works but has the side effect of moving the insertion point to the beginning of the textbox on the eleventh character for reasons that I don't understand.


The length is tested at nine as the KeyPress event occurs before "key" is added to the string and there seems to be no way of preventing it being added.

B4X:
Sub TextBox1_KeyPress (key)
   If StrLength(Textbox1.Text) >=9 Then
   Textbox1.Text= SubString(Textbox1.Text,0,9)
   End If
End Sub
 

agraham

Expert
Licensed User
Longtime User
I missed the obvious - this works nicely, the check for key >31 allows backspace editing of a full length textbox value.
B4X:
Sub TextBox1_KeyPress (key)
   If StrLength( textbox1.Text) >=10 Then
      If Asc(key)>31 Then
         Textbox1.IgnoreKey
      End If
   End If
End Sub
 
Last edited:

agraham

Expert
Licensed User
Longtime User
An improvement on my first method. I still don't understand why the insertion point moves but this code resets it. One advantage of this method is that if the user pastes in a string longer than the required length then if he tries to edit it the string is truncated which would not happen with the "ignorekey" method.

B4X:
Sub TextBox1_KeyPress (key)
    If StrLength( textbox1.Text) >=9 Then   
        If Asc(key)>31 Then
            Textbox1.Text= SubString(Textbox1.Text,0,9)
            Textbox1.SelectionStart = 9
        End If
    End If
End Sub

EDIT: The following is even better for user editing as the insertion point doesn't do unexpected things

B4X:
Sub TextBox1_KeyPress (key)
    If StrLength( textbox1.Text) >=9 Then   
        If Asc(key)>31 Then
            ss = Textbox1.SelectionStart
            Textbox1.Text= SubString(Textbox1.Text,0,9)
            Textbox1.SelectionStart = ss
        End If
    End If
End Sub

EDIT AGAIN!: I forgot that B4PPC 5.50 can now evaluate more complex logical conditions so the following is a little more elegant!

B4X:
Sub TextBox1_KeyPress (key) 
   If StrLength(textbox1.Text) >=9 AND Asc(key) > 31 Then   
      s = textbox1.SelectionStart
      Textbox1.Text= SubString(Textbox1.Text,0,9)
      textbox1.SelectionStart = s
   End If
End Sub
 
Last edited:
Top