Skip to content

Instantly share code, notes, and snippets.

@SuborbitalPigeon
Last active November 12, 2016 16:44
Show Gist options
  • Save SuborbitalPigeon/2925730 to your computer and use it in GitHub Desktop.
Save SuborbitalPigeon/2925730 to your computer and use it in GitHub Desktop.
Postcode validation using GJS or PyGObject
#!/usr/bin/gjs
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
var re = /[A-Z]{1,2}[\d][A-Z0-9]? ?[\d][A-Z]{2}/
const Postcode = new Lang.Class(
{
Name: 'Postcode',
_init: function()
{
this.application = new Gtk.Application();
this.application.connect('activate', Lang.bind(this, this._onActivate));
this.application.connect('startup', Lang.bind(this, this._onStartup));
},
_onActivate: function()
{
this._window.show_all();
},
_onStartup: function()
{
this._window = new Gtk.ApplicationWindow({ application: this.application,
title: "Postcode",
window_position: Gtk.WindowPosition.CENTER });
let entry = new Gtk.Entry({ secondary_icon_tooltip_text: "Not a valid postcode" });
entry.connect('changed', Lang.bind(this, this._onChanged));
this._window.add(entry);
},
_onChanged: function(editable)
{
let text = editable.get_chars(0, -1);
if (!text)
{
editable.secondary_icon_name = null;
return;
}
if (re.test(text))
editable.secondary_icon_name = null;
else
editable.secondary_icon_name = "dialog-warning-symbolic";
}
});
let app = new Postcode();
app.application.run(ARGV);
#!/usr/bin/env python
import re
from gi.repository import Gtk
class Postcode(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.set_title("Postcode")
self.connect("destroy", lambda w: Gtk.main_quit())
self.entry = Gtk.Entry()
self.entry.connect("changed", self._on_entry_changed)
self.entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, "Not a valid postcode")
self.add(self.entry)
self.regex = re.compile("[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}")
def _on_entry_changed(self, editable):
text = editable.get_chars(0, -1)
result = self.regex.match(text)
if text == "":
editable.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, None)
else:
if result == None:
editable.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "dialog-warning-symbolic")
else:
editable.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, None)
if __name__ == "__main__":
postcode = Postcode()
postcode.connect("destroy", lambda w: Gtk.main_quit())
postcode.show_all()
Gtk.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment