Errors when excluding characters from a LineEdit's text

Godot Version

v4.5.stable.official [876b29033]

Question

How can I exclude specified characters from a LineEdit’s text?

Context

The LineEdit is going to be used as a name that’s saved in as a file, so the \ / : ? “ < > and | keys will be excluded.
For whatever reason I am deciding to replace each invalid character with a fullstop

Previous Attempts

  1. I connected the text_changed signal, and using the String.replace() method to exclude the requested glyphs, then set the text to the modified text. Instead of removing specified characters, it moves the caret to the start of the line every time an edit is made. This is shown in the code below
  2. I never fully tested it, but I did see an option called “File” under Structured Text BiDi Override. I did give up on it, though, because the description mentioned how it was used for the text placements (e.g. reversing the horizontal placement for languages like Arabic)

Code

Clipped and modified to exclude unnecessary code
All excluded code does not interact with the issue
(Why am I specifying this, it’d already be implied, I’m sorry)

extends LineEdit

func _on_text_changed(new_text: String):
    new_text.replace("/", ".")
    new_text.replace("?", ".")
    # etc.
    text = new_text

Node modifications

Only including the modified properties
I hope that’s all that’s needed

Placeholder Text: “Type the name of your ruleset !!“
Max Length: 244
Emoji Menu Enabled: false
Caret Blink: true

Extra Note

Hello this is for the moderator
I requested a post for a topic a moment ago and I accidentally sent it before it was finished
It was called “Running into many errors when I try to exclude certain characters from a LineEdit’s text“
This is what I meant to send, so please ignore the other one
Also I’m sorry that this post is rough and beyond unprofessional
This is my first post, and I’m still getting used to interacting in this community
I apologize for the inconveniences inflicted upon the admins and users here
okay goodbye

Your code doesn’t assign the replacements to the new text, so your replacements don’t do anything. This would work though:

func _on_text_changed(new_text: String):
    new_text = new_text.replace("/", ".")
    new_text = new_text.replace("?", ".")
    # etc.
    text = new_text

You can move the caret yourself to the original spot after you make the replacements.

Here’s my corrected version, I also changed the replace() to replace_chars() to make it a one liner.

extends LineEdit

func _ready() -> void:
	text_changed.connect(_on_text_changed)

func _on_text_changed(new_text: String):
	var old_caret_column = caret_column
	text = new_text.replace_chars("/\\:?\"\'<>|", ".".unicode_at(0))
	caret_column = old_caret_column

No problem. I deleted the other post.

3 Likes