Limiting the number of characters during data entry

There are times when you might want to limit the number of characters a user can enter into a field. This lesson will show you how to control this.

The keyDown message

The keyDown message is sent whenever a character key is pressed, the message is sent to the focused field. The LiveCode engine must receive the keyDown message in order to respond to a typed character so trapping the message and not passing it prevents the user typing into the field.

The keyDown handler

When the user types into the field the keyDown handler checks to see if the field already contains the maximum number of character allowed. If the field already contains the maximum number of characters LiveCode beeps and doesn't pass the keyDown message which causes the key press to be lost.

If the field does not yet contain the maximum number of characters the keyDown message is passed, allowing it to proceed along the message path and be added to the field normally.

The me keyword

The keyword me refers to the object whose script contains the handler that is executing. In this case me refers to the field because the keyDown handler is in the field's script. When a field is referenced in this way LiveCode returns the contents of the field, the length of that content is the number of characters it contains. So the expression

the length of me 

is the number of characters in the field.

The keyDown code

The following handler belongs on the script of the entry field

on keyDown pKey
	if the length of me >= 5 then
		// If there are 5 or more characters in the field
		// beep and prevent text entry
		beep
	else
		// Allow text entry by passing the keyDown message
		pass keyDown
	end if
end keyDown

4 Comments

Carlos

what would happen with ctrl + v or del, you could have a command that detects a change in the content of the text that is different on text change because I already tried it and it does not work

Elanor Buchanan

Hi Carlos

You can do this by handling the textChanged message. This is sent after the text has changed so you could just beep or you could manually remove the extra characters from the field.

Alternatively you could add handlers for pasteKey, deleteKey, backspaceKey etc

I hope that helps.

Kind regards

Elanor

trevix

Hello and thanks for your help.
How do I limit the number of chars during data entry on a Android native field widget?
I tried with "textChanged", but after deleting the last char and updating the widget, the cursor get repositioned at the beginning of the text.

Panos Merakos

Hello Trevix,

Hmm, this might be a bug. Could you share your textChanged code?

Cheers

Add your comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.