Limiting Text Field input

BlitzPlus Forums/BlitzPlus Programming/Limiting Text Field input

Tyler(Posted 2005) [#1]
Anyone know how to set a maximum length of input for a text field? And to just numbers, for that matter? Thanks.

Say I wanted the user to only input 2 numbers, and ignore all the keystrokes afterward (except backspace), and any keystrokes that happened to be letters.


sswift(Posted 2005) [#2]
; -----------------------------------------------------------------------------------------------------------------------------------
; This function updates a text field.  It controls how many and which characters may be entered.
; It can also optionally force the text to change to display the minimum or maximum allowed value.
;
; If MaxLength is -1 then there is no maximum length allowed for the string in the textfield.
;
; AllowedChar$ is a string containing all characters allowed in the textfield.
; If AllowedChar$ is set to "" then the any character can be entered into the textfield.
;
; ForceValue is a boolean which determines if the function should override the text in the textfield and force it to be within
; the range of values specified, with the specified number of decimal places.  You should probably only do this when the user
; hits enter in the textfield, or the textfield loses focus.
; -----------------------------------------------------------------------------------------------------------------------------------
Function UpdateTextField(TextField, MaxLength, AllowedChars$="", ForceValue=False, MinValue#=0, MaxValue#=0, DecimalPlaces=0)

	Local Txt$
	Local Value#

	; Get the current text in the textfield.
		Txt$ = TextFieldText$(TextField)
	
	; Remove any characters from the textfield which the user is not allowed to enter.
		Txt$ = Allowed$(Txt$, AllowedChars$)

	; If the textfield should be forced into the desired range...

		If ForceValue = True
	
			; Get the current value of the textfield.			
				Value# = TextFieldText$(TextField)
							
			; Make sure the value is within the allowed range for this textfield.
				If Value# < MinValue# Then Value# = MinValue#
				If Value# > MaxValue# Then Value# = MaxValue#
		
			; Convert the value back into a string.
				If DecimalPlaces = 0 
					Txt$ = Int(Value#)
				Else
					Txt$ = Value#
					Txt$ = Left$(Txt$, Instr(Txt$, ".")+DecimalPlaces)
				EndIf
					
		EndIf

	; Truncate the string to the maximum allowed length.
		If (MaxLength > -1) Then Txt$ = Left$(Txt$, MaxLength)

	; Update the textfield.	
		SetGadgetText TextField, Txt$

End Function



Tyler(Posted 2005) [#3]
::Jaw drops:: Thank you!


sswift(Posted 2005) [#4]
Btw, you should call that when you get a gadget action event from the textfield. No need to call it every frame.