jquery.inputmask.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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.4.9 - dev
  7. This plugin is based on the masked input plugin written by Josh Bush (digitalbush.com)
  8. */
  9. (function($) {
  10. if ($.fn.inputmask == undefined) {
  11. $.inputmask = {
  12. //options default
  13. defaults: {
  14. placeholder: "_",
  15. optionalmarker: {
  16. start: "[",
  17. end: "]"
  18. },
  19. escapeChar: "\\",
  20. mask: null,
  21. oncomplete: null, //executes when the mask is complete
  22. onincomplete: null, //executes when the mask is incomplete and focus is lost
  23. oncleared: null, //executes when the mask is cleared
  24. repeat: 0, //repetitions of the mask
  25. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  26. patch_val: true, //override the jquery.val fn to detect changed in the inputmask by setting val(value)
  27. autoUnmask: false, //in combination with patch_val: true => automatically unmask when retrieving the value with $.fn.val
  28. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  29. clearMaskOnLostFocus: true,
  30. insertMode: true, //insert the input or overwrite the input
  31. clearIncomplete: false, //clear the incomplete input on blur
  32. aliases: {}, //aliases definitions => see jquery.inputmask.extentions.js
  33. definitions: {
  34. '9': {
  35. validator: "[0-9]",
  36. cardinality: 1
  37. },
  38. 'a': {
  39. validator: "[A-Za-z]",
  40. cardinality: 1
  41. },
  42. '*': {
  43. validator: "[A-Za-z0-9]",
  44. cardinality: 1
  45. }
  46. },
  47. 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,
  48. 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
  49. },
  50. ignorables: [8, 9, 13, 16, 17, 18, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 93, 106, 107, 108, 109, 110, 111]
  51. },
  52. val: $.fn.val //store the original jquery val function
  53. };
  54. $.fn.inputmask = function(fn, options) {
  55. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  56. var pasteEventName = $.browser.msie ? 'paste.inputmask' : 'input.inputmask';
  57. var iphone = navigator.userAgent.match(/iphone/i) != null;
  58. var android = navigator.userAgent.match(/android.*mobile safari.*/i) != null;
  59. if (android) {
  60. var browser = navigator.userAgent.match(/mobile safari.*/i);
  61. var version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  62. android = version <= 533;
  63. }
  64. var caretposCorrection = null;
  65. var _val = $.inputmask.val;
  66. if (opts.patch_val && $.fn.val.inputmaskpatch != true) {
  67. $.fn.val = function() {
  68. if (this.data('inputmask')) {
  69. if (this.data('inputmask')['autoUnmask'] && arguments.length == 0) {
  70. return this.inputmask('unmaskedvalue');
  71. }
  72. else {
  73. var result = _val.apply(this, arguments);
  74. if (arguments.length > 0) {
  75. this.triggerHandler('setvalue.inputmask');
  76. }
  77. return result;
  78. }
  79. }
  80. else {
  81. return _val.apply(this, arguments);
  82. }
  83. };
  84. $.extend($.fn.val, {
  85. inputmaskpatch: true
  86. });
  87. }
  88. if (typeof fn == "string") {
  89. switch (fn) {
  90. case "mask":
  91. //init buffer
  92. var _buffer = getMaskTemplate();
  93. var tests = getTestingChain();
  94. return this.each(function() {
  95. mask(this);
  96. });
  97. break;
  98. case "unmaskedvalue":
  99. var tests = this.data('inputmask')['tests'];
  100. var _buffer = this.data('inputmask')['_buffer'];
  101. opts.greedy = this.data('inputmask')['greedy'];
  102. opts.repeat = this.data('inputmask')['repeat'];
  103. opts.definitions = this.data('inputmask')['definitions'];
  104. return unmaskedvalue(this);
  105. break;
  106. case "setvalue":
  107. setvalue(this, options); //options in this case the value
  108. break;
  109. case "remove":
  110. var tests, _buffer;
  111. return this.each(function() {
  112. var input = $(this);
  113. if (input.data('inputmask')) {
  114. tests = input.data('inputmask')['tests'];
  115. _buffer = input.data('inputmask')['_buffer'];
  116. opts.greedy = input.data('inputmask')['greedy'];
  117. opts.repeat = input.data('inputmask')['repeat'];
  118. opts.definitions = input.data('inputmask')['definitions'];
  119. //writeout the unmaskedvalue
  120. _val.call(input, unmaskedvalue(input, true));
  121. //clear data
  122. input.removeData('inputmask');
  123. //unbind all events
  124. input.unbind(".inputmask");
  125. input.removeClass('focus.inputmask');
  126. }
  127. });
  128. break;
  129. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  130. if (this.data('inputmask'))
  131. return this.data('inputmask')['_buffer'].join('');
  132. else return "";
  133. default:
  134. //check if the fn is an alias
  135. if (!ResolveAlias(fn)) {
  136. //maybe fn is a mask so we try
  137. //set mask
  138. opts.mask = fn;
  139. }
  140. //init buffer
  141. var _buffer = getMaskTemplate();
  142. var tests = getTestingChain();
  143. return this.each(function() {
  144. mask(this);
  145. });
  146. break;
  147. }
  148. } if (typeof fn == "object") {
  149. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  150. //init buffer
  151. var _buffer = getMaskTemplate();
  152. var tests = getTestingChain();
  153. return this.each(function() {
  154. mask(this);
  155. });
  156. }
  157. //helper functions
  158. function ResolveAlias(aliasStr) {
  159. var aliasDefinition = opts.aliases[aliasStr];
  160. if (aliasDefinition)
  161. if (!aliasDefinition.alias) {
  162. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  163. return true;
  164. } else return ResolveAlias(aliasDefinition.alias); //alias is another alias
  165. return false;
  166. }
  167. function getMaskTemplate() {
  168. var escaped = false, outCount = 0;
  169. if (opts.mask.length == 1 && opts.greedy == false) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
  170. var singleMask = $.map(opts.mask.split(""), function(element, index) {
  171. var outElem = [];
  172. if (element == opts.escapeChar) {
  173. escaped = true;
  174. }
  175. else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
  176. var maskdef = opts.definitions[element];
  177. if (maskdef && !escaped) {
  178. for (i = 0; i < maskdef.cardinality; i++) {
  179. outElem.push(getPlaceHolder(outCount + i));
  180. }
  181. } else {
  182. outElem.push(element);
  183. escaped = false;
  184. }
  185. outCount += outElem.length;
  186. return outElem;
  187. }
  188. });
  189. //allocate repetitions
  190. var repeatedMask = singleMask.slice();
  191. for (var i = 1; i < opts.repeat && opts.greedy; i++) {
  192. repeatedMask = repeatedMask.concat(singleMask.slice());
  193. }
  194. return repeatedMask;
  195. }
  196. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int}
  197. function getTestingChain() {
  198. var isOptional = false, escaped = false;
  199. var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated
  200. return $.map(opts.mask.split(""), function(element, index) {
  201. var outElem = [];
  202. if (element == opts.escapeChar) {
  203. escaped = true;
  204. } else if (element == opts.optionalmarker.start && !escaped) {
  205. isOptional = true;
  206. newBlockMarker = true;
  207. }
  208. else if (element == opts.optionalmarker.end && !escaped) {
  209. isOptional = false;
  210. newBlockMarker = true;
  211. }
  212. else {
  213. var maskdef = opts.definitions[element];
  214. if (maskdef && !escaped) {
  215. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  216. for (i = 1; i < maskdef.cardinality; i++) {
  217. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  218. outElem.push({ fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function() { this.test = validator; } : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: isOptional, newBlockMarker: isOptional == true ? newBlockMarker : false, offset: 0, casing: maskdef["casing"] });
  219. if (isOptional == true) //reset newBlockMarker
  220. newBlockMarker = false;
  221. }
  222. outElem.push({ fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function() { this.test = maskdef.validator; } : new RegExp("."), cardinality: maskdef.cardinality, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: maskdef["casing"] });
  223. } else {
  224. outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null });
  225. escaped = false;
  226. }
  227. //reset newBlockMarker
  228. newBlockMarker = false;
  229. return outElem;
  230. }
  231. });
  232. }
  233. function isValid(pos, c, buffer) {
  234. if (pos < 0 || pos >= getMaskLength()) return false;
  235. var testPos = determineTestPosition(pos), loopend = c ? 1 : 0, chrs = '';
  236. for (var i = tests[testPos].cardinality; i > loopend; i--) {
  237. chrs += getBufferElement(buffer, testPos - (i - 1));
  238. }
  239. if (c) { chrs += c; }
  240. return tests[testPos].fn != null ? tests[testPos].fn.test(chrs, buffer) : false;
  241. }
  242. function isMask(pos) {
  243. var testPos = determineTestPosition(pos);
  244. var test = tests[testPos];
  245. return test != undefined ? test.fn : false;
  246. }
  247. function determineTestPosition(pos) {
  248. return pos % tests.length;
  249. }
  250. function getPlaceHolder(pos) {
  251. return opts.placeholder.charAt(pos % opts.placeholder.length);
  252. }
  253. function getMaskLength() {
  254. var calculatedLength = _buffer.length;
  255. if (!opts.greedy && opts.repeat > 1) {
  256. calculatedLength += (_buffer.length * (opts.repeat - 1))
  257. }
  258. return calculatedLength;
  259. }
  260. //pos: from position
  261. function seekNext(buffer, pos) {
  262. var maskL = getMaskLength();
  263. if (pos >= maskL) return maskL;
  264. var position = pos;
  265. while (++position < maskL && !isMask(position)) { };
  266. return position;
  267. }
  268. //pos: from position
  269. function seekPrevious(buffer, pos) {
  270. var position = pos;
  271. if (position <= 0) {
  272. if(isRTL && !opts.greedy)
  273. position = prepareBuffer(buffer, -1)
  274. return position;
  275. }
  276. while (--position > 0 && !isMask(position)) { };
  277. return position;
  278. }
  279. //these are needed to handle the non-greedy mask repetitions
  280. function setBufferElement(buffer, position, element) {
  281. position = prepareBuffer(buffer, position);
  282. var test = tests[determineTestPosition(position)];
  283. var elem = element;
  284. switch (test.casing) {
  285. case "upper":
  286. elem = element.toUpperCase();
  287. break;
  288. case "lower":
  289. elem = element.toLowerCase();
  290. break;
  291. }
  292. buffer[position] = elem;
  293. }
  294. function getBufferElement(buffer, position) {
  295. position = prepareBuffer(buffer, position);
  296. return buffer[position];
  297. }
  298. function prepareBuffer(buffer, position) {
  299. while ((buffer.length <= position || position < 0) && buffer.length < getMaskLength()) {
  300. var j = 0;
  301. if (isRTL) {
  302. j = _buffer.length -1;
  303. position = position + _buffer.length;
  304. while (_buffer[j] !== undefined)
  305. buffer.unshift(_buffer[j--]);
  306. } else while (_buffer[j] !== undefined) {
  307. buffer.push(_buffer[j++]);
  308. }
  309. }
  310. return position;
  311. }
  312. function writeBuffer(input, buffer, caretPos) {
  313. _val.call(input, buffer.join(''));
  314. if (caretPos != undefined) {
  315. if (android) {
  316. setTimeout(function() {
  317. caret(input, caretPos);
  318. }, 100);
  319. }
  320. else caret(input, caretPos);
  321. }
  322. };
  323. function clearBuffer(buffer, start, end) {
  324. for (var i = start, maskL = getMaskLength(); i < end && i < maskL; i++) {
  325. setBufferElement(buffer, i, getBufferElement(_buffer.slice(), i));
  326. }
  327. };
  328. function SetReTargetPlaceHolder(buffer, pos) {
  329. var testPos = determineTestPosition(pos);
  330. setBufferElement(buffer, pos, getBufferElement(_buffer, testPos));
  331. }
  332. function checkVal(input, buffer, clearInvalid) {
  333. var inputValue = TruncateInput(_val.call(input));
  334. clearBuffer(buffer, 0, buffer.length);
  335. buffer.length = _buffer.length;
  336. var lastMatch = -1, checkPosition = -1, maskL = getMaskLength(), ivl = inputValue.length, rtlMatch = ivl == 0 ? maskL : -1;
  337. for (var i = 0; i < ivl; i++) {
  338. for (var pos = checkPosition + 1; pos < maskL; pos++) {
  339. if (isMask(pos)) {
  340. var c = inputValue.charAt(i);
  341. if (isValid(pos, c, buffer) !== false) {
  342. setBufferElement(buffer, pos, c);
  343. lastMatch = checkPosition = pos;
  344. } else {
  345. SetReTargetPlaceHolder(buffer, pos);
  346. if (isMask(i) && c == getPlaceHolder(i)) {
  347. checkPosition = pos;
  348. rtlMatch = pos;
  349. }
  350. }
  351. break;
  352. } else { //nonmask
  353. SetReTargetPlaceHolder(buffer, pos);
  354. if (lastMatch == checkPosition) //once outsync the nonmask cannot be the lastmatch
  355. lastMatch = pos;
  356. checkPosition = pos;
  357. if (inputValue.charAt(i) == getBufferElement(buffer, pos))
  358. break;
  359. }
  360. }
  361. }
  362. if (clearInvalid) {
  363. writeBuffer(input, buffer);
  364. }
  365. return seekNext(buffer, isRTL ? rtlMatch : lastMatch);
  366. }
  367. function EscapeRegex(str) {
  368. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  369. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  370. }
  371. function TruncateInput(input) {
  372. return input.replace(new RegExp("(" + EscapeRegex(_buffer.join('')) + ")*$"), "");
  373. }
  374. //functionality fn
  375. function setvalue(el, value) {
  376. _val.call(el, value);
  377. el.triggerHandler('setvalue.inputmask');
  378. }
  379. function unmaskedvalue(el, skipDatepickerCheck) {
  380. if (tests && (skipDatepickerCheck === true || !el.hasClass('hasDatepicker'))) {
  381. var buffer = _buffer.slice();
  382. checkVal(el, buffer);
  383. return $.map(buffer, function(element, index) {
  384. return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null;
  385. }).join('');
  386. }
  387. else {
  388. return _val.call(el);
  389. }
  390. }
  391. function caret(input, begin, end) {
  392. var npt = input.jquery && input.length > 0 ? input[0] : input;
  393. if (typeof begin == 'number') {
  394. end = (typeof end == 'number') ? end : begin;
  395. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  396. if (npt.setSelectionRange) {
  397. npt.setSelectionRange(begin, end);
  398. } else if (npt.createTextRange) {
  399. var range = npt.createTextRange();
  400. range.collapse(true);
  401. range.moveEnd('character', end);
  402. range.moveStart('character', begin);
  403. range.select();
  404. }
  405. npt.focus();
  406. if (android && end != npt.selectionEnd) caretposCorrection = { begin: begin, end: end };
  407. } else {
  408. var caretpos = android ? caretposCorrection : null, caretposCorrection = null;
  409. if (caretpos == null) {
  410. if (npt.setSelectionRange) {
  411. begin = npt.selectionStart;
  412. end = npt.selectionEnd;
  413. } else if (document.selection && document.selection.createRange) {
  414. var range = document.selection.createRange();
  415. begin = 0 - range.duplicate().moveStart('character', -100000);
  416. end = begin + range.text.length;
  417. }
  418. caretpos = { begin: begin, end: end };
  419. }
  420. return caretpos;
  421. }
  422. };
  423. function mask(el) {
  424. var input = $(el);
  425. //store tests & original buffer in the input element - used to get the unmasked value
  426. input.data('inputmask', {
  427. 'tests': tests,
  428. '_buffer': _buffer,
  429. 'greedy': opts.greedy,
  430. 'repeat': opts.repeat,
  431. 'autoUnmask': opts.autoUnmask,
  432. 'definitions': opts.definitions
  433. });
  434. //init buffer
  435. var buffer = _buffer.slice(),
  436. undoBuffer = _val.call(input),
  437. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  438. lastPosition = -1,
  439. firstMaskPos = seekNext(buffer, -1)
  440. isRTL = false;
  441. if (el.dir == "rtl" || opts.numericInput) {
  442. el.dir = "ltr"
  443. input.css("text-align", "right");
  444. input.removeAttr("dir");
  445. isRTL = true;
  446. }
  447. //unbind all events - to make sure that no other mask will interfere when re-masking
  448. input.unbind(".inputmask");
  449. input.removeClass('focus.inputmask');
  450. //bind events
  451. if (!input.attr("readonly")) {
  452. input.bind("mouseenter.inputmask", function() {
  453. var input = $(this);
  454. if (!input.hasClass('focus.inputmask') && _val.call(input).length == 0) {
  455. buffer = _buffer.slice();
  456. writeBuffer(input, buffer);
  457. }
  458. }).bind("blur.inputmask", function() {
  459. var input = $(this);
  460. input.removeClass('focus.inputmask');
  461. if (_val.call(input) != undoBuffer) {
  462. input.change();
  463. }
  464. if (opts.clearMaskOnLostFocus && _val.call(input) == _buffer.join(''))
  465. _val.call(input, '');
  466. if ((opts.clearIncomplete || opts.onincomplete) && checkVal(input, buffer, true) != getMaskLength()) {
  467. if (opts.onincomplete) {
  468. opts.onincomplete.call(input);
  469. }
  470. if (opts.clearIncomplete) {
  471. if (opts.clearMaskOnLostFocus)
  472. _val.call(input, '');
  473. else {
  474. buffer = _buffer.slice();
  475. writeBuffer(input, buffer);
  476. }
  477. }
  478. }
  479. }).bind("focus.inputmask", function() {
  480. var input = $(this);
  481. input.addClass('focus.inputmask');
  482. undoBuffer = _val.call(input);
  483. }).bind("mouseleave.inputmask", function() {
  484. var input = $(this);
  485. if (opts.clearMaskOnLostFocus && !input.hasClass('focus.inputmask') && _val.call(input) == _buffer.join(''))
  486. _val.call(input, '');
  487. }).bind("click.inputmask", function() {
  488. var input = $(this);
  489. setTimeout(function() {
  490. var selectedCaret = caret(input);
  491. if (selectedCaret.begin == selectedCaret.end) {
  492. var clickPosition = selectedCaret.begin;
  493. lastPosition = checkVal(input, buffer, false);
  494. if (isRTL)
  495. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer) || !isMask(clickPosition)) ? clickPosition : lastPosition);
  496. else
  497. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer) || !isMask(clickPosition)) ? clickPosition : lastPosition);
  498. }
  499. }, 0);
  500. }).bind('dblclick.inputmask', function() {
  501. var input = $(this);
  502. setTimeout(function() {
  503. caret(input, 0, lastPosition);
  504. }, 0);
  505. }).bind("keydown.inputmask", keydownEvent
  506. ).bind("keypress.inputmask", keypressEvent
  507. ).bind("keyup.inputmask", function(e) {
  508. var input = $(this);
  509. var k = e.keyCode;
  510. if (k == opts.keyCode.TAB && input.hasClass('focus.inputmask') && _val.call(input).length == 0) {
  511. buffer = _buffer.slice();
  512. writeBuffer(input, buffer);
  513. if (!isRTL) caret(input, 0);
  514. }
  515. }).bind(pasteEventName, function() {
  516. var input = $(this);
  517. setTimeout(function() {
  518. caret(input, checkVal(input, buffer, true));
  519. }, 0);
  520. }).bind('setvalue.inputmask', function() {
  521. var input = $(this);
  522. setTimeout(function() {
  523. undoBuffer = _val.call(input);
  524. checkVal(input, buffer, true);
  525. if (_val.call(input) == _buffer.join(''))
  526. _val.call(input, '');
  527. }, 0);
  528. });
  529. }
  530. setTimeout(function() {
  531. lastPosition = checkVal(input, buffer, true);
  532. if (document.activeElement === input[0]) { //position the caret when in focus
  533. input.addClass('focus.inputmask');
  534. caret(input, lastPosition);
  535. } else if (opts.clearMaskOnLostFocus && _val.call(input) == _buffer.join(''))
  536. _val.call(input, '');
  537. }, 0);
  538. //private functions
  539. //shift chars to left from start to end and put c at end position if defined
  540. function shiftL(start, end, c) {
  541. while (!isMask(start) && start - 1 >= 0) start--;
  542. for (var i = start; i <= end && i < getMaskLength(); i++) {
  543. if (isMask(i)) {
  544. SetReTargetPlaceHolder(buffer, i);
  545. var j = seekNext(buffer, i);
  546. var p = getBufferElement(buffer, j);
  547. if (p != getPlaceHolder(j)) {
  548. if (j < getMaskLength() && isValid(i, p, buffer) !== false) {
  549. setBufferElement(buffer, i, getBufferElement(buffer, j));
  550. } else {
  551. if (isMask(i))
  552. break;
  553. }
  554. } else if (c == undefined) break;
  555. } else {
  556. SetReTargetPlaceHolder(buffer, i);
  557. }
  558. }
  559. if (c != undefined)
  560. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  561. buffer = TruncateInput(buffer.join('')).split('');
  562. if (buffer.length == 0) buffer = _buffer.slice();
  563. return start; //return the used start position
  564. }
  565. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  566. for (var i = start; i <= end && i < getMaskLength(); i++) {
  567. if (isMask(i)) {
  568. var t = getBufferElement(buffer, i);
  569. setBufferElement(buffer, i, c);
  570. if (t != getPlaceHolder(i)) {
  571. var j = seekNext(buffer, i);
  572. if (j < getMaskLength()) {
  573. if (isValid(j, t, buffer) !== false)
  574. c = t;
  575. else {
  576. if (isMask(j))
  577. break;
  578. else c = t;
  579. }
  580. } else break;
  581. } else if (full !== true) break;
  582. } else
  583. SetReTargetPlaceHolder(buffer, i);
  584. }
  585. };
  586. function keydownEvent(e) {
  587. //Safari 5.1.x - modal dialog fires keypress twice workaround
  588. skipKeyPressEvent = false;
  589. var input = $(this), k = e.keyCode, pos = caret(input);
  590. //delete selection before proceeding
  591. if (((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) && (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
  592. clearBuffer(buffer, pos.begin, pos.end);
  593. //backspace, delete, and escape get special treatment
  594. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  595. var maskL = getMaskLength();
  596. if (pos.begin == 0 && pos.end == maskL) {
  597. buffer = _buffer.slice();
  598. writeBuffer(input, buffer);
  599. if (!isRTL) caret(input, 0);
  600. } else {
  601. var beginPos = pos.begin - (k == opts.keyCode.DELETE ? 0 : 1);
  602. if (isRTL) {
  603. shiftR(0, beginPos, getPlaceHolder(0), true);
  604. if (k == opts.keyCode.BACKSPACE) {
  605. beginPos++;
  606. }
  607. } else beginPos = shiftL(beginPos < 0 ? 0 : beginPos, maskL);
  608. writeBuffer(input, buffer, beginPos);
  609. }
  610. if (opts.oncleared && _val.call(input) == _buffer.join(''))
  611. opts.oncleared.call(input);
  612. return false;
  613. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  614. setTimeout(function() {
  615. var caretPos = checkVal(input, buffer, false);
  616. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  617. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  618. }, 0);
  619. return false;
  620. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  621. caret(input, 0, e.shiftKey ? pos.begin : 0);
  622. return false;
  623. }
  624. else if (k == opts.keyCode.ESCAPE) {//escape
  625. _val.call(input, undoBuffer);
  626. caret(input, 0, checkVal(input, buffer));
  627. return false;
  628. } else if (k == opts.keyCode.INSERT) {//insert
  629. opts.insertMode = !opts.insertMode;
  630. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  631. return false;
  632. }
  633. else if (!opts.insertMode) { //overwritemode
  634. if (k == opts.keyCode.RIGHT) {//right
  635. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  636. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  637. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  638. return false;
  639. } else if (k == opts.keyCode.LEFT) {//left
  640. var caretPos = pos.begin - 1;
  641. caretPos = caretPos > 0 ? caretPos : 0;
  642. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  643. return false;
  644. }
  645. }
  646. }
  647. function keypressEvent(e) {
  648. //Safari 5.1.x - modal dialog fires keypress twice workaround
  649. if (skipKeyPressEvent) return false;
  650. skipKeyPressEvent = true;
  651. var input = $(this);
  652. e = e || window.event;
  653. var k = e.which || e.charCode || e.keyCode;
  654. if (e.ctrlKey || e.altKey || e.metaKey || $.inArray(k, opts.ignorables) != -1) {//Ignore
  655. return true;
  656. } else {
  657. if (k) {
  658. var pos = caret(input), c = String.fromCharCode(k), maskL = getMaskLength();
  659. if (isRTL) {
  660. var p = seekPrevious(buffer, pos.end);
  661. if (isValid(p, c, buffer)) {
  662. if (isValid(firstMaskPos, buffer[firstMaskPos], buffer) == false || (opts.greedy === false && buffer.length < maskL)) {
  663. shiftL(firstMaskPos, p, c);
  664. writeBuffer(input, buffer, opts.numericInput ? pos.end : p);
  665. } else if (opts.oncomplete)
  666. opts.oncomplete.call(input);
  667. } else if (android) writeBuffer(input, buffer, pos.begin);
  668. }
  669. else {
  670. var p = seekNext(buffer, pos.begin - 1);
  671. if (isValid(p, c, buffer)) {
  672. if (opts.insertMode == true) shiftR(p, maskL, c); else setBufferElement(buffer, p, c);
  673. var next = seekNext(buffer, p);
  674. writeBuffer(input, buffer, next);
  675. if (opts.oncomplete && next == maskL)
  676. opts.oncomplete.call(input);
  677. } else if (android) writeBuffer(input, buffer, pos.begin);
  678. }
  679. return false;
  680. }
  681. }
  682. }
  683. }
  684. };
  685. }
  686. })(jQuery);