How to add a character limit to text edit node?

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

I need their to be a character limit for the text edit node. I tried:

func _on_TextEdit_text_changed():
    if get_text().length() > character_limit:
	    readonly = true

But the problem is that then the text can not be edited again. I want the player to be able to go back and delete text again.

:bust_in_silhouette: Reply From: Eric Ellingson

This seems to work pretty well.

export(int) var LIMIT = 10
var current_text = ''
var cursor_line = 0
var cursor_column = 0

func _on_TextEdit_text_changed():
    var new_text : String = $Control/TextEdit.text
    if new_text.length() > LIMIT:
	    $Control/TextEdit.text = current_text
	    # when replacing the text, the cursor will get moved to the beginning of the
	    # text, so move it back to where it was 
	    $Control/TextEdit.cursor_set_line(cursor_line)
	    $Control/TextEdit.cursor_set_column(cursor_column)

    current_text = $Control/TextEdit.text
    # save current position of cursor for when we have reached the limit
    cursor_line = $Control/TextEdit.cursor_get_line()
    cursor_column = $Control/TextEdit.cursor_get_column()

Thank you that works perfectly!

GoGirlGaming | 2019-04-24 17:01

Are there any disadvantages of ignoring the cursor and all?

func cropLineToMaxLength(maxLength: int) -> void:
  var inputText := get_line(0)
  if inputText.length() > maxLength:
	set_line(0, inputText.substr(0, maxLength))


func _on_Input_text_changed() -> void:
  cropLineToMaxLength(3)

And I think it would clarify the purpose if it was connected directly to the respective TextEdit Node instead of to the Control, would it not?

Dri | 2021-05-24 16:17