Created
September 10, 2012 17:50
-
-
Save kkamkou/3692491 to your computer and use it in GitHub Desktop.
Input normalization for the URN field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"