LiveCode LessonsHow To - LiveCode Sample Scripts TextLimiting the number of characters during data entry

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

0 Comments

Add your comment

E-Mail me when someone replies to this comment