GTK+ FAQ
<<< Previous | Development with GTK+: widget specific questions | Next >>>

# How do I validate/limit/filter the input to a GtkEntry? [GTK 2.x]

If you want to validate the text that a user enters into a GtkEntry widget you can attach to the "insert_text" signal of the entry, and modify the text within the callback function. The example below forces all characters to uppercase, and limits the range of characters to A-Z. Note that the entry is cast to an object of type GtkEditable, from which GtkEntry is derived.

    #include <ctype.h>
    #include <gtk/gtk.h>

    void insert_text_handler (GtkEntry    *entry,
                              const gchar *text,
                              gint         length,
                              gint        *position,
                              gpointer     data)
    {
      GtkEditable *editable = GTK_EDITABLE(entry);
      int i, count=0;
      gchar *result = g_new (gchar, length);

      for (i=0; i < length; i++) {
        if (!isalpha(text[i]))
          continue;
        result[count++] = islower(text[i]) ? toupper(text[i]) : text[i];
      }

      if (count > 0) {
        g_signal_handlers_block_by_func (G_OBJECT (editable),
                                         G_CALLBACK (insert_text_handler),
                                         data);
        gtk_editable_insert_text (editable, result, count, position);
        g_signal_handlers_unblock_by_func (G_OBJECT (editable),
                                           G_CALLBACK (insert_text_handler),
                                           data);
      }
      g_signal_stop_emission_by_name (G_OBJECT (editable), "insert_text");

      g_free (result);
    }

    int main (int   argc,
              char *argv[])
    {
      GtkWidget *window;
      GtkWidget *entry;

      gtk_init (&argc, &argv);

      /* create a new window */
      window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
      gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
      g_signal_connect (G_OBJECT (window), "destroy",
                        G_CALLBACK (gtk_main_quit),
                        NULL);

      entry = gtk_entry_new();
      g_signal_connect(G_OBJECT(entry), "insert_text",
    		     G_CALLBACK(insert_text_handler),
    		     NULL);
      gtk_container_add(GTK_CONTAINER (window), entry);
      gtk_widget_show(entry);

      gtk_widget_show(window);

      gtk_main();
      return(0);
    }

<<< Previous | Home | Next >>>
How do I make a GtkEntry widget activate on pressing the Return key? | Up | How do I use horizontal scrollbars with a GtkText widget?