Skip to content

Instantly share code, notes, and snippets.

@kkamkou
Created September 10, 2012 17:50
Show Gist options
  • Save kkamkou/3692491 to your computer and use it in GitHub Desktop.
Save kkamkou/3692491 to your computer and use it in GitHub Desktop.
Input normalization for the URN field
/**
* @author Kanstantsin A Kamkou (2ka.by)
*
* Example:
* $('#myField').urn();
* $('#myField').urn({on: 'keyup'});
*/
(function ($) {
"use strict";
// jQuery plugin
$.fn.urn = function (options) {
var skipList = [8, 16, 35, 36, 37, 38, 39, 40],
options = $.extend({'on': 'blur'}, options);
return this.on(options.on, function (event) {
// some key-skips
if ($.inArray(event.keyCode, skipList) !== -1) {
return false;
}
var $self = $(this),
value = $.trim($self.val());
// lowercase convert
value = value.toLowerCase();
// spaces to -
value = value.replace(/\s+/g, '-');
// only alphanumeric
value = value.replace(/[^\w\/-]/g, '');
// trailing - and _ chars
value = value.replace(/(-|_)+/g, '$01');
// chars after the slash
value = value.replace(/([._\/-]+)?\/+([._\/-]+)?/g, '/');
// chars at the beginning and at the end
value = value.replace(/^[._\/-]+|[._\/-]+$/g, '');
// value update
$self.val(value);
return true;
});
};
}(jQuery));
@kkamkou
Copy link
Author

kkamkou commented Jun 15, 2013

This plugin is useful when you are working with a rewrite-field(an input field for the web-address of a publication). It'll clear the value of it.

Example: "ASdasdE #*$&342" to "asdasde-342"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment