TextField max length

BlitzMax Forums/MaxGUI Module/TextField max length

GfK(Posted 2010) [#1]
Is there a way to restrict the input length of a text field to N characters?


Oddball(Posted 2010) [#2]
You could possibly do it with SetGadgetFilter and just ignore key presses after the max length is reached.


Ghost Dancer(Posted 2010) [#3]
You can indeed use setFilter to do this. I recently had to code one myself :)

SetGadgetFilter(myTextgadget, lengthFilter)	'set the filter
SetGadgetExtra myTextgadget, "10"		'use gadget extra to store max field length

Function lengthFilter(event:TEvent, context:Object)
	Local sourceGadget:TGadget = TGadget(event.source)
	Local txtLen = Len( GadgetText(sourceGadget) )
	Local maxLen = Int( String( GadgetExtra(sourceGadget) ) )
	
	If txtLen < maxLen Then Return True
	
	'check for non-displayable keys
	Select Event.ID
	Case EVENT_KEYCHAR, EVENT_KEYDOWN
		If Event.Data = KEY_DELETE Then Return True
		If Event.Data = KEY_RETURN Then Return True
		If Event.Data => KEY_LEFT And Event.Data <= KEY_DOWN Then Return True
		If Event.Data = KEY_BACKSPACE Then Return True
		If Event.Data = KEY_HOME Then Return True
		If Event.Data = KEY_END Then Return True
		If Event.Data = KEY_TAB Then Return True
		If Event.Mods Then Return True
	End Select
	
	Return False
End Function



GfK(Posted 2010) [#4]
Jeez, is that the only way?!

Seems awfully convoluted for what achieving what should be basic functionality of a text field??


GfK(Posted 2010) [#5]
Just tested that code and it does kinda work, unless you paste something into a limited field, then the limit is ignored.


Ghost Dancer(Posted 2010) [#6]
Ah, well spotted. I'm currently only using it to restrict input to 1 character so didn't think of pasting.

I think the only way to test it is to call a function on EVENT_GADGETACTION, and crop the text.


jsp(Posted 2010) [#7]
If you filter the CTRL key in the filter function, pasting wouldn't be allowed. If that helps...


Ghost Dancer(Posted 2010) [#8]
Here you go, just call this from your event code on EVENT_GADGETACTION:

Function cropLength(sourceGadget:TGadget)
	Local txtLen = Len( GadgetText(sourceGadget) )
	Local maxLen = Int( String( GadgetExtra(sourceGadget) ) )
	
	If txtLen > maxLen Then SetGadgetText sourceGadget, Left(GadgetText(sourceGadget), maxLen)
	
End Function



Ghost Dancer(Posted 2010) [#9]
You can disable the Ctrl key, but you would lose the key nav provided by that key (e.g. Ctrl Left/Right). Its nice to keep all the gadget functionality if at all possible :)


jsp(Posted 2010) [#10]
Yep, but if it's only a two digit value or something in the textfield, it may not hurt.


GfK(Posted 2010) [#11]
If you filter the CTRL key in the filter function, pasting wouldn't be allowed
That wouldn't stop anybody using right-click>Paste.

Thanks all!