Making a textbox only have numbers

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I have a TextBox, and I want it so when I type a letter or symbol in, it deletes it, but if I type a number in, it keeps the number. (Basically a text box that only lets you type numbers)

  2. What is the issue? Include screenshots / videos if possible!
    I tried making a script to do it, however

  • The script does not work for detecting a non-number
  • If it did work for that, it would clear the whole thing, but I only want it to clear the last letter you typed.
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried making a script, but as I said above, it didn’t work.

Script: (Under the TextBox)

local box = script.Parent

box:GetPropertyChangedSignal("Text"):Connect(function()
    local text = tonumber(box.Text)
    if not text then
        box.Text = string.sub(box.Text,string.len(box.Text))
    end
end)

If you want to remove every character that isn’t a number in a string, you can use patterns

local str = "hello123"
local withoutNonNumbers = string.gsub(str, "%D", "")
print(withoutNonNumbers)
1 Like

So, this script would remove the letters in a TextBox?

local box = script.Parent

box:GetPropertyChangedSignal("Text"):Connect(function()
    box.Text = string.gsub(box.Text, "%D", "")
end)
1 Like

Yeah, but the issue is that it might cause a stack overflow error, since you are changing the text inside of a property changed signal, which fires the signal again.

local box = script.Parent
local isPlayerEditing = true

box:GetPropertyChangedSignal("Text"):Connect(function()
    if isPlayerEditing then
        isPlayerEditing = false
        box.Text = string.gsub(box.Text, "%D", "")
        isPlayerEditing = true
    end
end)

You can either use something similar to that, or listen to FocusLost

7 Likes