Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Only allow numbers in text box?

Hello, I have a text box where you can donate points to your team. And obviously, the game will break if you donate a string to an int value. So, how can I make it possible to only be able to write numbers in the text box?

Please don't take this question down, I have looked everything up, and this is my last resort,

BTW THIS IS NOT A REQUEST, I JUST WANT TO KNOW WHAT STRING MANIPULATION I NEED TO USE AND HOW I USE IT!

Thank you.

2 answers

✓ Accepted answer

SummerEquinox's answer probably works, but here's a much simpler way

TextBox:GetPropertyChangedSignal("Text"):Connect(function()
	if tonumber(TextBox.Text) then
		-- send the donation
	else
		TextBox.Text = "Enter a number to donate" -- do not send the donation
	end
end)

tonumber is a Lua function that checks if the string can be turned into a number. It is related to tostring if you've heard of that

Note: tonumber returns nil if it can't convert the string to a number, but if it can then it returns the string converted to a number

6 comments

0

You should also mention to number returns nil if it cannot concert its arguments to a number. Good answer nonetheless

0

convert*

0

This is definitely the more ideal solution, I kind of jumped on string manipulation since he mentioned it. OP use this instead.

0

But what if I dont want to allow negative numbers either??

0

Should I just use: if newValue < 0 then...

0

Well, I think you would want newValue >= 0 but yeah that’s the way to do it

Say you have a TextBox - you can allow only numbers (where num >0) to be typed in it with the following code:

function Format(t)
	return t:gsub("%D", "")
end

script.Parent:GetPropertyChangedSignal("Text"):Connect(function()
	script.Parent.Text = Format(script.Parent.Text)
end)

If you wanted to check the text afterwards - you could do:

script.Parent.FocusLost:Connect(function()
	if string.match(script.Parent.Text, "%D+") then
		print('Text is not a positive number')
		script.Parent.Text = "TextBox"
	end
end)

1 comment

0

Respect

This discussion is preserved as it was. New answers, comments, and votes are closed.