+1 vote

I have a node which is a Canvas control / LineEdit.

I'm expecting... a user will put an id number, ie:
01
02
1000
etc.

If someone does enter string characters in... I'd like to be able to validate that and tell them "sorry, numbers only".

There is no try/catch in gdscript that I'm aware of - so I can't use that and then use the except section to say : "sorry, numbers only".

Is there a better way to handle this?

I'd use a OptionButton.... but at 1000+ ID's ... it makes for far too long of a list.

Godot version 3
in Engine by (133 points)

2 Answers

0 votes
Best answer

You should use a SpinBox, and get the number by going:

$SpinBox.value

With this method, the user can't enter non-integer chars.

Hope this helps.

by (246 points)
selected by

Thank you - I'm worried 1 to 1000 maybe too large of list to spin through, but I will look into this in detail. I've never used the SpinBox, so thank you, I'm excited to check it out.

It'll be fine if you make the SpinBox large enough! (eg. increasing the width so that you can fit the '1000' in it). Note that you can do anything that you can do with LineEdits with SpinBoxes, EXCEPT enter strings, and you need to retrieve the number with .value rather than .text.

0 votes

First, connect your LineEdit signal, you can choose text_changed if you want to validate everytime user types something on it or text_entered if you want to validate it when user has finished typing.

On your signal function put this:

$LineEdit.text = str(float($LineEdit.text)

This will convert your text to float then reconvert it back to string again. However, it won't tell user "Sorry, number only", if you want to do that then you will have check every character and check their ord.
The ord of 0 is 48 and the ord of 9 is 57. So it will be like this

var text = $LineEdit.text
var i = 0
while text[i] != "":
   if ord(text[i]) >= 48 and ord(text[i]) <= 57:
      # Do something if current char is a number
   else:
      print("Sorry, number only")
      # Do something if current char is not a number

   i += 1
by (27 points)

Thank you - I will look into this in detail.

I found this to be a simple answer to what I was trying to do - thank you very much.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.