Limit Characters in a Textbox when Typing

I simply want to set a maximum length on a textbox so that when the user gets to that point, they cannot type any more. Evidently, the Maximum Characters property doesn’t actually prevent someone from continuing to type (which is misleading in the documentation).

I tried to capture keystrokes and keep count and remove the last character if they’ve exceeded the limit, but then I have to reset focus to the end of the typed characters because the focus resets when I update the field. And if I turn off Reject Updates During Edit, I can’t update the field at all while I’m typing.

I can’t believe this very simple UI function is missing, so please tell me that I’m wrong!

Thanks!

Add an integer custom property to the field to hold your length limit (doesn’t work with the built-in). I used altMax for the following:

if event.propertyName == 'text':
	tf = event.source
	print event
	if tf.focusOwner and tf.altMax > 1:
		if len(event.newValue) >= tf.altMax:
			tf.select(tf.altMax-1, len(event.newValue))
			if len(event.newValue) > tf.altMax:
				tf.replaceSelection(event.newValue[tf.altMax-1])

Turn off defer updates and reject updates.

1 Like

Simple with a regex pattern. Use a Formatted Text Field and use

^[\pL\pN]{0,5}+$

for the regex pattern. Then uncheck the Allows Invalid Text property.This regex will allow any alphanumeric and limit the input between 0 and 5 characters long. Change as needed.

Thank you both. That second solution is very succinct and exactly what I needed.

This worked great for me for a Vision Text Area, thanks!

1 Like