Limit input characters in an entry

I want to make a Gtk.Entry field that can only accept numbers. Is that what GtkInputPurpose is for? The docs say:

Note that the purpose is not meant to impose a totally strict rule about allowed characters, and does not replace input validation.

I’m willing to still do the validation. I just want to give the user quicker feedback on what characters are allowed. This is similar to HTML’s <input type="number">.

1 Like

I see that in this topic, someone is doing this manually by listening to the onInsertText signal. Is this the only way to do it or does GTK offer this as a built-in feature, via GtkInputPurpose or something else?

No, GTK does not provide validation out of the box. You’re supposed to perform validation every time the text changes—usually by connecting to the notify::text signal.

1 Like

I don’t know if this can help you but I use this function in the insert-text signal

on_format_number (GtkEditable *editable,
                  const gchar *text,
                  gint        length,
                  gint        *position,
                  gpointer    user_data)
  if (g_unichar_isdigit (g_utf8_get_char (text)))
          g_signal_handlers_block_by_func (editable,
                                           (gpointer) on_format_number,
          gtk_editable_insert_text (editable,
          g_signal_handlers_unblock_by_func (editable,
                                             (gpointer) on_format_number,
  g_signal_stop_emission_by_name (editable, "insert_text");

Ok, thank you very much! I’ll try that.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.