How can I only allowed numbers in a TextBox?

hello! I’m making a script that will let the player choose a FOV within a number range. how could I make that the player only enters numbers into the TextBox? and how can I return to the previous FOV they had if they do use letters?

another question is if making it a slider would just be better? and if it is how would I do such a thing?

1 Like

Try the following:

local textBox = script.Parent -- or wherever

function stripNonNumbers()
	textBox.Text = textBox.Text:gsub("%D","")
end

textBox:GetPropertyChangedSignal("Text"):Connect(stripNonNumbers)

textBox:GetPropertyChangedSignal("Text"):Connect(stripNonNumbers) will detect whenever the text is changed and call stripNonNumbers

textBox.Text:gsub("%D","") replaces anything that is not a digit with an empty string, effectively removing non-numbers.


If you want it instead to return it to the previous FOV, you could use this instead:

local textBox = script.Parent -- or wherever

local lastFov = 100

function setFov()
	local newFov = tonumber(textBox.Text)
	if newFov then
		lastFov = newFov
		camera ... --[[or whatver]] ... fov = newFov
	else
		textBox.Text = lastFov
	end
end

textBox.FocusLost:Connect(setFov)

Now, setFov is called whenever the user clicks off of the textbox and it gets the value inputted as a number.

If the number is valid, it sets the last valid fov (lastFov) and you can make it set the camera’s fov there.

If the number is invalid, then the textbox’s text is set to the last valid fov.

3 Likes

can you explain what this does? I don’t understand what “gsub” does.

Yes, sorry I was editing it with the updated information.

Now I have finished

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.