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

# How do I validate/limit/filter the input to a GtkEntry?

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) {
        gtk_signal_handler_block_by_func (GTK_OBJECT (editable),
    				      GTK_SIGNAL_FUNC (insert_text_handler),
    				      data);
        gtk_editable_insert_text (editable, result, count, position);
        gtk_signal_handler_unblock_by_func (GTK_OBJECT (editable),
    					GTK_SIGNAL_FUNC (insert_text_handler),
    					data);
      }
      gtk_signal_emit_stop_by_name (GTK_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");
      gtk_signal_connect(GTK_OBJECT (window), "delete_event",
    		     (GtkSignalFunc) gtk_exit, NULL);

      entry = gtk_entry_new();
      gtk_signal_connect(GTK_OBJECT(entry), "insert_text",
    		     GTK_SIGNAL_FUNC(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?