LineEdit - how can I make sure I'm only getting number input, or at least validate it ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mattkw80

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

I’m expecting… a user will put an id number, ie:

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.

:bust_in_silhouette: Reply From: AlphinAlbukhari

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
      print("Sorry, number only")
      # Do something if current char is not a number
   i += 1

Thank you - I will look into this in detail.

mattkw80 | 2021-08-07 17:55

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

mattkw80 | 2021-08-08 03:38

:bust_in_silhouette: Reply From: Snail0259

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


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

Hope this helps.

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.

mattkw80 | 2021-08-07 17:56

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.

Snail0259 | 2021-08-07 23:28