Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active December 4, 2017 15:42
Show Gist options
  • Save choonkeat/dac397dbcdc8f531cb49 to your computer and use it in GitHub Desktop.
Save choonkeat/dac397dbcdc8f531cb49 to your computer and use it in GitHub Desktop.
jQuery.autocomplete + Fuse.js = Lighter version of mailcheck
//= require fuse.min
$(function() {
var defaultDomains = [{"host":"yahoo.com"},{"host":"google.com"},{"host":"hotmail.com"},{"host":"gmail.com"},
{"host":"me.com"},{"host":"aol.com"},{"host":"mac.com"},{"host":"live.com"},{"host":"comcast.net"},
{"host":"googlemail.com"},{"host":"msn.com"},{"host":"hotmail.co.uk"},{"host":"yahoo.co.uk"},{"host":"facebook.com"},
{"host":"verizon.net"},{"host":"sbcglobal.net"},{"host":"att.net"},{"host":"gmx.com"},{"host":"mail.com"},
{"host":"outlook.com"},{"host":"icloud.com"}];
var fuse = new Fuse(defaultDomains, {
caseSensitive: false,
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
keys: ["host"]
});
$( "input[type='email']" ).autocomplete({
delay: 0,
source: function(req, callback) {
var index = req.term.indexOf("@");
if (index == -1) return callback();
var username = req.term.substring(0, index);
var hostname = req.term.substring(index+1);
var domain = null;
var options = [];
$.each(defaultDomains, function(index, obj) {
if (obj.host.toLowerCase() == hostname.toLowerCase()) domain = hostname;
});
if (domain) {
// exact match: don't offer autocomplete
} else {
$.each(fuse.search(hostname), function(index, obj) {
domain = obj.host;
options.push({value: [username, '@', domain].join(''), label: domain});
});
}
callback(options);
}
}).on('blur', function(event) {
event.target.value = event.target.value.replace(/[,]/, '.');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment