Any way to make a character limit on a TextBox based on the TextBox's size?

So I have a TextBox here, and it automatically expands based on the amount of text inside of it. I am trying to make it so you can’t enter anymore text after a certain size is reached. Here’s an image of what it looks like:


What I have tried is this:

if script.Parent.TextBounds.Magnitude >,13).Magnitude then
	script.Parent.Text = script.Parent.Text:sub(1,#script.Parent.Text)

But that doesn’t work because the number of text automatically updates everytime new text is added due to it being inside of a TextChanged function. So is there any way for me to do this?

1 Like

local len = #script.Parent.Text;
local limit = 10;
script.Parent.Text = script.Parent.Text:sub(1,math.clamp(len,0,limit));

1 Like

I’m not really that great working with Text but here’s a method:

First, you will have to know an average size for each character. You can use the TextService:GetTextSize() method for this. When the TextChanged event fires, you can calculate the difference between the X Size you want for the TextBox and the current size of the TextBox. Divide the difference by the X Value of the Vector2 you get from the TextService:GetTextSize() method to get the no of characters extra.
Then you should be able to do:

script.Parent.Text = script.Parent.Text:sub(1,#script.Parent.Text - NoOfCharactersExtra)

I haven’t really tried this so I’m not sure if this will work. Also, I’m sure there’s a much easier way to do this; This method seems unnecessarily complicated. :sweat_smile:

That wouldn’t work because the limit is specific, I want the limit to be the amount of text before the highest magnitude is reached.

Ah, in that case you’ll have to use the textservice like @rohithsuju12345 mentioned to get the length of the text in pixels

Just saying I solved it, this is what I did. I made a table, it could be called anything but I called it numtext. Then inside of the TextChanged function that I had I put an if statement magnitude check to check if the TextBox’s magnitude is bigger than the maximum I set, then if it is it would insert a number into the numtext table which would be the number when the maximum magnitude is reached, I then did text:sub(1,numtext[1]) and it now works.