How do I use string manipulation to limit textbox input to letters and numbers only?

I’m trying to make a menu where a player can choose their own username. For example, coolguy23123.

How do I make it so the textbox only accepts alphabetical (letters) or numerical text only?

For example, a person can create usernames like this: “1Bob213” or “jem3Efdw” or “2k9d2e”
But a user should not be able to create usernames like this: “j32.2f” or “@#$abc” or “:sunglasses::sunglasses:

There is a string pattern to do that called “%w” which accepts any alphanumeric character, numbers or letters basically, even both.

You could make so when the player presses enter to stop focusing on a Textbox, it checks the string to see if it’s alphanumeric and if it is, give it the username, else, do whatever you want when it’s not

Or alternatively, you could use %W, which is for anything that isn’t a number or a letter, you can use that to see if your string matches it via string.match and if it returns nil (found no match), then it means their chosen username is fully alphanumeric, otherwise, if it does return something, it means they inputted something that isn’t a letter or a number, so you can do something

Here’s an example

local test = "This is quite the test 👍👍👍👍👍👍"
test = test:gsub(" ", "") --Remove spaces
local e = string.match(test, "%W") --Check for non alphanumerics
print(e) --Return result
5 Likes

To add onto @EmbatTheHybrid, I would suggest utilizing the String Patterns Reference page on the Developer Hub for additional info, as that outlines the official character classes for Lua along with specific examples that explain how they can be used.

1 Like

Like above said, you have to filter the characters, you can use GetPropertyChangedSignal of TextBox in order to do this.

local TextBox = script.Parent;

local function Filter()
local Filtered = TextBox.Text:gsub('%p+',''):gsub('%s+','');
TextBox.Text = Filtered and Filtered:match('%w+') or '';
end;

TextBox:GetPropertyChangedSignal("Text"):Connect(Filter)
1 Like