TextField max length
BlitzMax Forums/MaxGUI Module/TextField max length
| ||
Is there a way to restrict the input length of a text field to N characters? |
| ||
You could possibly do it with SetGadgetFilter and just ignore key presses after the max length is reached. |
| ||
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 |
| ||
Jeez, is that the only way?! Seems awfully convoluted for what achieving what should be basic functionality of a text field?? |
| ||
Just tested that code and it does kinda work, unless you paste something into a limited field, then the limit is ignored. |
| ||
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. |
| ||
If you filter the CTRL key in the filter function, pasting wouldn't be allowed. If that helps... |
| ||
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 |
| ||
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 :) |
| ||
Yep, but if it's only a two digit value or something in the textfield, it may not hurt. |
| ||
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! |