jquery.inputmask.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. Input Mask plugin for jquery
  3. http://github.com/RobinHerbots/jquery.inputmask
  4. Copyright (c) 2010 Robin Herbots
  5. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. Version: 0.2.3
  7. This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
  8. */
  9. (function($) {
  10. $.inputmask = {
  11. //options default
  12. defaults: {
  13. placeholder: "_",
  14. optionalmarker: {
  15. start: "[",
  16. end: "]"
  17. },
  18. mask: null,
  19. oncomplete: null,
  20. repeat: 0, //repetitions of the mask
  21. greedy: true, //true: allocated buffer for all mask repetitions - false: allocate only if needed
  22. patch_val: true, //override the jquery.val fn to detect changed in the inputmask by setting val(value)
  23. autounmask: false, //in combination with patch_val: true => automatically unmask when retrieving the value with $.fn.val
  24. definitions: {
  25. '9': {
  26. "validator": "[0-9]",
  27. "cardinality": 1,
  28. 'prevalidator': null
  29. },
  30. 'a': {
  31. "validator": "[A-Za-z]",
  32. "cardinality": 1,
  33. "prevalidator": null
  34. },
  35. '*': {
  36. "validator": "[A-Za-z0-9]",
  37. "cardinality": 1,
  38. "prevalidator": null
  39. },
  40. 'd': { //day
  41. "validator": "0[1-9]|[12][0-9]|3[01]",
  42. "cardinality": 2,
  43. "prevalidator": [{ "validator": "[0-3]", "cardinality": 1}]
  44. },
  45. 'm': { //month
  46. "validator": "0[1-9]|1[012]",
  47. "cardinality": 2,
  48. "prevalidator": [{ "validator": "[01]", "cardinality": 1}]
  49. },
  50. 'y': { //year
  51. "validator": "(19|20)\\d\\d",
  52. "cardinality": 4,
  53. "prevalidator": [
  54. { "validator": "[12]", "cardinality": 1 },
  55. { "validator": "(19|20)", "cardinality": 2 },
  56. { "validator": "(19|20)\\d", "cardinality": 3 }
  57. ]
  58. }
  59. },
  60. keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108,
  61. NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91
  62. }
  63. },
  64. val: $.fn.val //store the original jquery val function
  65. };
  66. $.fn.inputmask = function(fn, options) {
  67. var opts = $.extend({}, $.inputmask.defaults, options);
  68. var pasteEventName = $.browser.msie ? 'paste.inputmask' : 'input.inputmask';
  69. var iPhone = (window.orientation != undefined);
  70. var _val = $.inputmask.val;
  71. if (opts.patch_val && $.fn.val.inputmaskpatch != true) {
  72. $.fn.val = function() {
  73. if (this.data('inputmask')) {
  74. if (this.data('autounmask') && arguments.length == 0) {
  75. return this.inputmask('unmaskedvalue');
  76. }
  77. else {
  78. var result = _val.apply(this, arguments);
  79. if (arguments.length > 0) {
  80. this.triggerHandler('setvalue.inputmask');
  81. }
  82. return result;
  83. }
  84. }
  85. else {
  86. return _val.apply(this, arguments);
  87. }
  88. };
  89. $.extend($.fn.val, {
  90. inputmaskpatch: true
  91. });
  92. }
  93. if (typeof fn == "string") {
  94. if (fn == 'mask') {
  95. //init buffer
  96. var _buffer = getMaskTemplate();
  97. var tests = getTestingChain();
  98. return this.each(function() {
  99. mask($(this));
  100. });
  101. } else if (fn == 'unmaskedvalue') {
  102. var tests = this.data('tests');
  103. var _buffer = this.data('_buffer');
  104. opts.greedy = this.data('greedy');
  105. opts.repeat = this.data('repeat');
  106. return unmaskedvalue(this);
  107. } else if (fn == 'setvalue') {
  108. setvalue(this, options); //options in this case the value
  109. }
  110. else { //maybe fn is a mask so we try
  111. //set mask
  112. opts.mask = fn;
  113. //init buffer
  114. var _buffer = getMaskTemplate();
  115. var tests = getTestingChain();
  116. return this.each(function() {
  117. mask($(this));
  118. });
  119. }
  120. } if (typeof fn == "object") {
  121. opts = $.extend({}, $.inputmask.defaults, fn);
  122. //init buffer
  123. var _buffer = getMaskTemplate();
  124. var tests = getTestingChain();
  125. return this.each(function() {
  126. mask($(this));
  127. });
  128. }
  129. //helper functions
  130. function getMaskTemplate() {
  131. var singleMask = $.map(opts.mask.split(""), function(element, index) {
  132. var outElem = [];
  133. if (element != opts.optionalmarker.start && element != opts.optionalmarker.end) {
  134. var maskdef = opts.definitions[element];
  135. if (maskdef) {
  136. for (i = 0; i < maskdef.cardinality; i++) {
  137. outElem.push(opts.placeholder);
  138. }
  139. } else outElem.push(element);
  140. return outElem;
  141. }
  142. });
  143. //allocate repetitions
  144. var repeatedMask = singleMask.slice();
  145. for (var i = 0; i < opts.repeat && opts.greedy; i++) {
  146. repeatedMask = repeatedMask.concat(singleMask.slice());
  147. }
  148. return repeatedMask;
  149. }
  150. //test definition => [regex, cardinality, optionality]
  151. function getTestingChain() {
  152. var isOptional = false;
  153. return $.map(opts.mask.split(""), function(element, index) {
  154. var outElem = [];
  155. if (element == opts.optionalmarker.start) isOptional = true;
  156. else if (element == opts.optionalmarker.end) isOptional = false;
  157. else {
  158. var maskdef = opts.definitions[element];
  159. if (maskdef) {
  160. for (i = 1; i < maskdef.cardinality; i++) {
  161. var prevalidator = maskdef.prevalidator[i - 1];
  162. outElem.push([new RegExp(prevalidator.validator), prevalidator.cardinality, isOptional]);
  163. }
  164. outElem.push([new RegExp(maskdef.validator), maskdef.cardinality, isOptional]);
  165. } else outElem.push(null);
  166. return outElem;
  167. }
  168. });
  169. }
  170. function isValid(pos, c, buffer) {
  171. var testPos = determineTestPosition(pos);
  172. var loopend = 0;
  173. if (c) { loopend = 1; ; }
  174. var chrs = '';
  175. for (var i = tests[testPos][1]; i > loopend; i--) {
  176. chrs += getBufferElement(buffer, testPos - (i - 1));
  177. }
  178. if (c) { chrs += c; }
  179. return tests[testPos][0].test(chrs);
  180. }
  181. function isMask(pos) {
  182. return tests[determineTestPosition(pos)];
  183. }
  184. function determineTestPosition(pos) {
  185. return pos % tests.length;
  186. }
  187. function getMaskLength() {
  188. var calculatedLength = _buffer.length;
  189. if (!opts.greedy) {
  190. calculatedLength += (_buffer.length * opts.repeat)
  191. }
  192. return calculatedLength;
  193. }
  194. function seekNext(pos) {
  195. while (++pos <= getMaskLength() && !isMask(pos));
  196. return pos;
  197. }
  198. //these are needed to handle the non-greedy mask repetitions
  199. function setBufferElement(buffer, position, element) {
  200. while (buffer.length <= position && buffer.length < getMaskLength()) {
  201. $.merge(buffer, _buffer);
  202. }
  203. buffer[position] = element;
  204. }
  205. function getBufferElement(buffer, position) {
  206. while (buffer.length <= position && buffer.length < getMaskLength()) {
  207. $.merge(buffer, _buffer);
  208. }
  209. return buffer[position];
  210. }
  211. function writeBuffer(input, buffer) { return _val.call(_val.call(input, buffer.join(''))); };
  212. function clearBuffer(buffer, start, end) {
  213. for (var i = start; i < end && i < getMaskLength(); i++) {
  214. setBufferElement(buffer, i, getBufferElement(_buffer.slice(), i));
  215. }
  216. };
  217. function checkVal(input, buffer, clearInvalid) {
  218. var inputValue = _val.call(input).replace(new RegExp("(" + _buffer.join('') + ")*$"), "");
  219. clearBuffer(buffer, 0, buffer.length);
  220. buffer.length = _buffer.length; //reset the buffer to its original size
  221. var lastMatch = -1;
  222. for (var i = 0; i < inputValue.length; i++) {
  223. for (var pos = lastMatch + 1; pos < getMaskLength(); pos++) {
  224. if (isMask(pos)) {
  225. if (isValid(pos, inputValue.charAt(i), buffer)) {
  226. setBufferElement(buffer, pos, inputValue.charAt(i));
  227. lastMatch = pos;
  228. } else {
  229. setBufferElement(buffer, pos, opts.placeholder);
  230. }
  231. break;
  232. } else { //nonmask
  233. lastMatch++;
  234. }
  235. }
  236. }
  237. if (clearInvalid) {
  238. writeBuffer(input, buffer);
  239. }
  240. return seekNext(lastMatch);
  241. }
  242. //functionality fn
  243. function setvalue(el, value) {
  244. _val.call(el, value);
  245. el.triggerHandler('setvalue.inputmask');
  246. }
  247. function unmaskedvalue(el) {
  248. if (tests && !el.hasClass('hasDatepicker')) {
  249. var buffer = _buffer.slice();
  250. checkVal(el, buffer);
  251. return $.map(buffer, function(element, index) {
  252. return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null;
  253. }).join('');
  254. }
  255. else {
  256. return _val.call(el);
  257. }
  258. }
  259. function mask(el) {
  260. var input = $(el);
  261. //store tests & original buffer in the input element - used to get the unmasked value
  262. input.data('tests', tests);
  263. input.data('_buffer', _buffer);
  264. input.data('greedy', opts.greedy);
  265. input.data('repeat', opts.repeat);
  266. input.data('inputmask', true);
  267. input.data('autounmask', opts.autounmask);
  268. //init buffer
  269. var buffer = _buffer.slice();
  270. var undoBuffer = _val.call(input);
  271. var ignore = false; //Variable for ignoring control keys
  272. var lastPosition = -1;
  273. //unbind all events - to make sure that no other mask will interfere when re-masking
  274. input.unbind(".inputmask");
  275. input.removeClass('focus.inputmask');
  276. //bind events
  277. if (!input.attr("readonly")) {
  278. input.bind("mouseenter.inputmask", function() {
  279. if (!input.hasClass('focus.inputmask') && _val.call(input).length == 0) {
  280. buffer = _buffer.slice();
  281. writeBuffer(input, buffer);
  282. }
  283. }).bind("blur.inputmask", function() {
  284. input.removeClass('focus.inputmask');
  285. setTimeout(function() {
  286. if (_val.call(input) == _buffer.join(''))
  287. _val.call(input, '');
  288. else if (_val.call(input) != undoBuffer) {
  289. input.change();
  290. }
  291. }, 0);
  292. }).bind("focus.inputmask", function() {
  293. input.addClass('focus.inputmask');
  294. undoBuffer = _val.call(input);
  295. }).bind("mouseleave.inputmask", function() {
  296. if (!input.hasClass('focus.inputmask') && _val.call(input) == _buffer.join(''))
  297. _val.call(input, '');
  298. }).bind("click.inputmask", function() {
  299. setTimeout(function() {
  300. lastPosition = checkVal(input, buffer, true);
  301. caret(input, lastPosition);
  302. }, 0);
  303. }).bind('dblclick.inputmask', function() {
  304. setTimeout(function() {
  305. caret(input, 0, lastPosition);
  306. }, 0);
  307. }).bind("keydown.inputmask", keydownEvent
  308. ).bind("keypress.inputmask", keypressEvent
  309. ).bind(pasteEventName, function() {
  310. setTimeout(function() {
  311. caret(input, checkVal(input, buffer, true));
  312. }, 0);
  313. }).bind('setvalue.inputmask', function() {
  314. setTimeout(function() {
  315. checkVal(input, buffer, true);
  316. if (_val.call(input) == _buffer.join(''))
  317. _val.call(input, '');
  318. }, 0);
  319. });
  320. }
  321. setTimeout(function() {
  322. checkVal(input, buffer, true);
  323. if (_val.call(input) == _buffer.join(''))
  324. _val.call(input, '');
  325. }, 0);
  326. //private functions
  327. function shiftL(pos) {
  328. while (!isMask(pos) && --pos >= 0);
  329. for (var i = pos; i < getMaskLength(); i++) {
  330. if (isMask(i)) {
  331. setBufferElement(buffer, i, opts.placeholder);
  332. var j = seekNext(i);
  333. if (j < getMaskLength() && isValid(i, getBufferElement(buffer, j), buffer)) {
  334. setBufferElement(buffer, i, getBufferElement(buffer, j));
  335. } else
  336. break;
  337. }
  338. }
  339. buffer = buffer.join('').replace(new RegExp("(" + _buffer.join('') + ")*$"), "").split('');
  340. if (buffer.length == 0) buffer = _buffer.slice();
  341. writeBuffer(input, buffer);
  342. caret(input, pos);
  343. };
  344. function shiftR(pos) {
  345. for (var i = pos, c = opts.placeholder; i < getMaskLength(); i++) {
  346. if (isMask(i)) {
  347. var j = seekNext(i);
  348. var t = getBufferElement(buffer, i);
  349. setBufferElement(buffer, i, c);
  350. if (j < getMaskLength() && isValid(j, t, buffer))
  351. c = t;
  352. else
  353. break;
  354. }
  355. }
  356. };
  357. function caret(input, begin, end) {
  358. if (input.length == 0) return;
  359. if (typeof begin == 'number') {
  360. end = (typeof end == 'number') ? end : begin;
  361. return input.each(function() {
  362. if (this.setSelectionRange) {
  363. this.focus();
  364. this.setSelectionRange(begin, end);
  365. } else if (this.createTextRange) {
  366. var range = this.createTextRange();
  367. range.collapse(true);
  368. range.moveEnd('character', end);
  369. range.moveStart('character', begin);
  370. range.select();
  371. }
  372. });
  373. } else {
  374. if (input[0].setSelectionRange) {
  375. begin = input[0].selectionStart;
  376. end = input[0].selectionEnd;
  377. } else if (document.selection && document.selection.createRange) {
  378. var range = document.selection.createRange();
  379. begin = 0 - range.duplicate().moveStart('character', -100000);
  380. end = begin + range.text.length;
  381. }
  382. return { begin: begin, end: end };
  383. }
  384. };
  385. function keydownEvent(e) {
  386. var pos = caret($(this));
  387. var k = e.keyCode;
  388. ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));
  389. //delete selection before proceeding
  390. if ((pos.begin - pos.end) != 0 && (!ignore || k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
  391. clearBuffer(buffer, pos.begin, pos.end);
  392. //backspace, delete, and escape get special treatment
  393. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iPhone && k == 127)) {//backspace/delete
  394. shiftL(pos.begin + (k == opts.keyCode.DELETE ? 0 : -1));
  395. return false;
  396. } else if (k == opts.keyCode.ESCAPE) {//escape
  397. _val.call(input, undoBuffer);
  398. caret(input, 0, checkVal(input, buffer));
  399. return false;
  400. }
  401. }
  402. function keypressEvent(e) {
  403. if (ignore) {
  404. ignore = false;
  405. //Fixes Mac FF bug on backspace
  406. return (e.keyCode == opts.keyCode.BACKSPACE) ? false : null;
  407. }
  408. e = e || window.event;
  409. var k = e.charCode || e.keyCode || e.which;
  410. var pos = caret($(this));
  411. if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
  412. return true;
  413. } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
  414. var p = seekNext(pos.begin - 1);
  415. if (p < getMaskLength()) {
  416. var c = String.fromCharCode(k);
  417. if (isValid(p, c, buffer)) {
  418. shiftR(p);
  419. setBufferElement(buffer, p, c);
  420. writeBuffer(input, buffer);
  421. var next = seekNext(p);
  422. caret($(this), next);
  423. if (opts.oncomplete && next == getMaskLength())
  424. opts.oncomplete.call(input);
  425. }
  426. }
  427. }
  428. return false;
  429. }
  430. }
  431. };
  432. })(jQuery);