jquery.inputmask.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. if (pos <= 0) {
  271. if(isRTL && !opts.greedy)
  272. prepareBuffer(buffer, -1)
  273. return 0;
  274. }
  275. var position = pos;
  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. 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. 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. while (_buffer[j] !== undefined)
  304. buffer.unshift(_buffer[j--]);
  305. } else while (_buffer[j] !== undefined) {
  306. buffer.push(_buffer[j++]);
  307. }
  308. }
  309. }
  310. function writeBuffer(input, buffer, caretPos) {
  311. _val.call(input, buffer.join(''));
  312. if (caretPos != undefined) {
  313. if (android) {
  314. setTimeout(function() {
  315. caret(input, caretPos);
  316. }, 100);
  317. }
  318. else caret(input, caretPos);
  319. }
  320. };
  321. function clearBuffer(buffer, start, end) {
  322. for (var i = start, maskL = getMaskLength(); i < end && i < maskL; i++) {
  323. setBufferElement(buffer, i, getBufferElement(_buffer.slice(), i));
  324. }
  325. };
  326. function SetReTargetPlaceHolder(buffer, pos) {
  327. var testPos = determineTestPosition(pos);
  328. setBufferElement(buffer, pos, getBufferElement(_buffer, testPos));
  329. }
  330. function checkVal(input, buffer, clearInvalid) {
  331. var inputValue = TruncateInput(_val.call(input));
  332. clearBuffer(buffer, 0, buffer.length);
  333. buffer.length = _buffer.length;
  334. var lastMatch = -1, checkPosition = -1, maskL = getMaskLength(), ivl = inputValue.length, rtlMatch = ivl == 0 ? maskL : -1;
  335. for (var i = 0; i < ivl; i++) {
  336. for (var pos = checkPosition + 1; pos < maskL; pos++) {
  337. if (isMask(pos)) {
  338. var c = inputValue.charAt(i);
  339. if (isValid(pos, c, buffer) !== false) {
  340. setBufferElement(buffer, pos, c);
  341. lastMatch = checkPosition = pos;
  342. } else {
  343. SetReTargetPlaceHolder(buffer, pos);
  344. if (isMask(i) && c == getPlaceHolder(i)) {
  345. checkPosition = pos;
  346. rtlMatch = pos;
  347. }
  348. }
  349. break;
  350. } else { //nonmask
  351. SetReTargetPlaceHolder(buffer, pos);
  352. if (lastMatch == checkPosition) //once outsync the nonmask cannot be the lastmatch
  353. lastMatch = pos;
  354. checkPosition = pos;
  355. if (inputValue.charAt(i) == getBufferElement(buffer, pos))
  356. break;
  357. }
  358. }
  359. }
  360. if (clearInvalid) {
  361. writeBuffer(input, buffer);
  362. }
  363. return seekNext(buffer, isRTL ? rtlMatch : lastMatch);
  364. }
  365. function EscapeRegex(str) {
  366. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  367. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  368. }
  369. function TruncateInput(input) {
  370. return input.replace(new RegExp("(" + EscapeRegex(_buffer.join('')) + ")*$"), "");
  371. }
  372. //functionality fn
  373. function setvalue(el, value) {
  374. _val.call(el, value);
  375. el.triggerHandler('setvalue.inputmask');
  376. }
  377. function unmaskedvalue(el, skipDatepickerCheck) {
  378. if (tests && (skipDatepickerCheck === true || !el.hasClass('hasDatepicker'))) {
  379. var buffer = _buffer.slice();
  380. checkVal(el, buffer);
  381. return $.map(buffer, function(element, index) {
  382. return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null;
  383. }).join('');
  384. }
  385. else {
  386. return _val.call(el);
  387. }
  388. }
  389. function caret(input, begin, end) {
  390. var npt = input.jquery && input.length > 0 ? input[0] : input;
  391. if (typeof begin == 'number') {
  392. end = (typeof end == 'number') ? end : begin;
  393. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  394. if (npt.setSelectionRange) {
  395. npt.setSelectionRange(begin, end);
  396. } else if (npt.createTextRange) {
  397. var range = npt.createTextRange();
  398. range.collapse(true);
  399. range.moveEnd('character', end);
  400. range.moveStart('character', begin);
  401. range.select();
  402. }
  403. npt.focus();
  404. if (android && end != npt.selectionEnd) caretposCorrection = { begin: begin, end: end };
  405. } else {
  406. var caretpos = android ? caretposCorrection : null, caretposCorrection = null;
  407. if (caretpos == null) {
  408. if (npt.setSelectionRange) {
  409. begin = npt.selectionStart;
  410. end = npt.selectionEnd;
  411. } else if (document.selection && document.selection.createRange) {
  412. var range = document.selection.createRange();
  413. begin = 0 - range.duplicate().moveStart('character', -100000);
  414. end = begin + range.text.length;
  415. }
  416. caretpos = { begin: begin, end: end };
  417. }
  418. return caretpos;
  419. }
  420. };
  421. function mask(el) {
  422. var input = $(el);
  423. //store tests & original buffer in the input element - used to get the unmasked value
  424. input.data('inputmask', {
  425. 'tests': tests,
  426. '_buffer': _buffer,
  427. 'greedy': opts.greedy,
  428. 'repeat': opts.repeat,
  429. 'autoUnmask': opts.autoUnmask,
  430. 'definitions': opts.definitions
  431. });
  432. //init buffer
  433. var buffer = _buffer.slice(),
  434. undoBuffer = _val.call(input),
  435. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  436. lastPosition = -1,
  437. firstMaskPos = seekNext(buffer, -1)
  438. isRTL = false;
  439. if (el.dir == "rtl" || opts.numericInput) {
  440. el.dir = "ltr"
  441. input.css("text-align", "right");
  442. input.removeAttr("dir");
  443. isRTL = true;
  444. }
  445. //unbind all events - to make sure that no other mask will interfere when re-masking
  446. input.unbind(".inputmask");
  447. input.removeClass('focus.inputmask');
  448. //bind events
  449. if (!input.attr("readonly")) {
  450. input.bind("mouseenter.inputmask", function() {
  451. var input = $(this);
  452. if (!input.hasClass('focus.inputmask') && _val.call(input).length == 0) {
  453. buffer = _buffer.slice();
  454. writeBuffer(input, buffer);
  455. }
  456. }).bind("blur.inputmask", function() {
  457. var input = $(this);
  458. input.removeClass('focus.inputmask');
  459. if (_val.call(input) != undoBuffer) {
  460. input.change();
  461. }
  462. if (opts.clearMaskOnLostFocus && _val.call(input) == _buffer.join(''))
  463. _val.call(input, '');
  464. if ((opts.clearIncomplete || opts.onincomplete) && checkVal(input, buffer, true) != getMaskLength()) {
  465. if (opts.onincomplete) {
  466. opts.onincomplete.call(input);
  467. }
  468. if (opts.clearIncomplete) {
  469. if (opts.clearMaskOnLostFocus)
  470. _val.call(input, '');
  471. else {
  472. buffer = _buffer.slice();
  473. writeBuffer(input, buffer);
  474. }
  475. }
  476. }
  477. }).bind("focus.inputmask", function() {
  478. var input = $(this);
  479. input.addClass('focus.inputmask');
  480. undoBuffer = _val.call(input);
  481. }).bind("mouseleave.inputmask", function() {
  482. var input = $(this);
  483. if (opts.clearMaskOnLostFocus && !input.hasClass('focus.inputmask') && _val.call(input) == _buffer.join(''))
  484. _val.call(input, '');
  485. }).bind("click.inputmask", function() {
  486. var input = $(this);
  487. setTimeout(function() {
  488. var selectedCaret = caret(input);
  489. if (selectedCaret.begin == selectedCaret.end) {
  490. var clickPosition = selectedCaret.begin;
  491. lastPosition = checkVal(input, buffer, false);
  492. if (isRTL)
  493. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer) || !isMask(clickPosition)) ? clickPosition : lastPosition);
  494. else
  495. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer) || !isMask(clickPosition)) ? clickPosition : lastPosition);
  496. }
  497. }, 0);
  498. }).bind('dblclick.inputmask', function() {
  499. var input = $(this);
  500. setTimeout(function() {
  501. caret(input, 0, lastPosition);
  502. }, 0);
  503. }).bind("keydown.inputmask", keydownEvent
  504. ).bind("keypress.inputmask", keypressEvent
  505. ).bind("keyup.inputmask", function(e) {
  506. var input = $(this);
  507. var k = e.keyCode;
  508. if (k == opts.keyCode.TAB && input.hasClass('focus.inputmask') && _val.call(input).length == 0) {
  509. buffer = _buffer.slice();
  510. writeBuffer(input, buffer);
  511. if (!isRTL) caret(input, 0);
  512. }
  513. }).bind(pasteEventName, function() {
  514. var input = $(this);
  515. setTimeout(function() {
  516. caret(input, checkVal(input, buffer, true));
  517. }, 0);
  518. }).bind('setvalue.inputmask', function() {
  519. var input = $(this);
  520. setTimeout(function() {
  521. undoBuffer = _val.call(input);
  522. checkVal(input, buffer, true);
  523. if (_val.call(input) == _buffer.join(''))
  524. _val.call(input, '');
  525. }, 0);
  526. });
  527. }
  528. setTimeout(function() {
  529. lastPosition = checkVal(input, buffer, true);
  530. if (document.activeElement === input[0]) { //position the caret when in focus
  531. input.addClass('focus.inputmask');
  532. caret(input, lastPosition);
  533. } else if (opts.clearMaskOnLostFocus && _val.call(input) == _buffer.join(''))
  534. _val.call(input, '');
  535. }, 0);
  536. //private functions
  537. //shift chars to left from start to end and put c at end position if defined
  538. function shiftL(start, end, c) {
  539. while (!isMask(start) && start - 1 >= 0) start--;
  540. for (var i = start; i <= end && i < getMaskLength(); i++) {
  541. if (isMask(i)) {
  542. SetReTargetPlaceHolder(buffer, i);
  543. var j = seekNext(buffer, i);
  544. var p = getBufferElement(buffer, j);
  545. if (p != getPlaceHolder(j)) {
  546. if (j < getMaskLength() && isValid(i, p, buffer) !== false) {
  547. setBufferElement(buffer, i, getBufferElement(buffer, j));
  548. } else {
  549. if (isMask(i))
  550. break;
  551. }
  552. } else if (c == undefined) break;
  553. } else {
  554. SetReTargetPlaceHolder(buffer, i);
  555. }
  556. }
  557. if (c != undefined)
  558. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  559. buffer = TruncateInput(buffer.join('')).split('');
  560. if (buffer.length == 0) buffer = _buffer.slice();
  561. return start; //return the used start position
  562. }
  563. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  564. for (var i = start; i <= end && i < getMaskLength(); i++) {
  565. if (isMask(i)) {
  566. var t = getBufferElement(buffer, i);
  567. setBufferElement(buffer, i, c);
  568. if (t != getPlaceHolder(i)) {
  569. var j = seekNext(buffer, i);
  570. if (j < getMaskLength()) {
  571. if (isValid(j, t, buffer) !== false)
  572. c = t;
  573. else {
  574. if (isMask(j))
  575. break;
  576. else c = t;
  577. }
  578. } else break;
  579. } else if (full !== true) break;
  580. } else
  581. SetReTargetPlaceHolder(buffer, i);
  582. }
  583. };
  584. function keydownEvent(e) {
  585. //Safari 5.1.x - modal dialog fires keypress twice workaround
  586. skipKeyPressEvent = false;
  587. var input = $(this), k = e.keyCode, pos = caret(input);
  588. //delete selection before proceeding
  589. if (((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) && (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE))
  590. clearBuffer(buffer, pos.begin, pos.end);
  591. //backspace, delete, and escape get special treatment
  592. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  593. var maskL = getMaskLength();
  594. if (pos.begin == 0 && pos.end == maskL) {
  595. buffer = _buffer.slice();
  596. writeBuffer(input, buffer);
  597. if (!isRTL) caret(input, 0);
  598. } else {
  599. var beginPos = pos.begin - (k == opts.keyCode.DELETE ? 0 : 1);
  600. if (isRTL) {
  601. shiftR(0, beginPos, getPlaceHolder(0), true);
  602. if (k == opts.keyCode.BACKSPACE) {
  603. beginPos++;
  604. }
  605. } else beginPos = shiftL(beginPos < 0 ? 0 : beginPos, maskL);
  606. writeBuffer(input, buffer, beginPos);
  607. }
  608. if (opts.oncleared && _val.call(input) == _buffer.join(''))
  609. opts.oncleared.call(input);
  610. return false;
  611. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  612. setTimeout(function() {
  613. var caretPos = checkVal(input, buffer, false);
  614. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  615. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  616. }, 0);
  617. return false;
  618. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  619. caret(input, 0, e.shiftKey ? pos.begin : 0);
  620. return false;
  621. }
  622. else if (k == opts.keyCode.ESCAPE) {//escape
  623. _val.call(input, undoBuffer);
  624. caret(input, 0, checkVal(input, buffer));
  625. return false;
  626. } else if (k == opts.keyCode.INSERT) {//insert
  627. opts.insertMode = !opts.insertMode;
  628. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  629. return false;
  630. }
  631. else if (!opts.insertMode) { //overwritemode
  632. if (k == opts.keyCode.RIGHT) {//right
  633. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  634. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  635. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  636. return false;
  637. } else if (k == opts.keyCode.LEFT) {//left
  638. var caretPos = pos.begin - 1;
  639. caretPos = caretPos > 0 ? caretPos : 0;
  640. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  641. return false;
  642. }
  643. }
  644. }
  645. function keypressEvent(e) {
  646. //Safari 5.1.x - modal dialog fires keypress twice workaround
  647. if (skipKeyPressEvent) return false;
  648. skipKeyPressEvent = true;
  649. var input = $(this);
  650. e = e || window.event;
  651. var k = e.which || e.charCode || e.keyCode;
  652. if (e.ctrlKey || e.altKey || e.metaKey || $.inArray(k, opts.ignorables) != -1) {//Ignore
  653. return true;
  654. } else {
  655. if (k) {
  656. var pos = caret(input), c = String.fromCharCode(k), maskL = getMaskLength();
  657. if (isRTL) {
  658. var p = seekPrevious(buffer, pos.end);
  659. if (isValid(p, c, buffer)) {
  660. if (isValid(firstMaskPos, buffer[firstMaskPos], buffer) == false || (opts.greedy === false && buffer.length < maskL)) {
  661. shiftL(firstMaskPos, p, c);
  662. writeBuffer(input, buffer, opts.numericInput ? pos.end : p);
  663. } else if (opts.oncomplete)
  664. opts.oncomplete.call(input);
  665. } else if (android) writeBuffer(input, buffer, pos.begin);
  666. }
  667. else {
  668. var p = seekNext(buffer, pos.begin - 1);
  669. if (isValid(p, c, buffer)) {
  670. if (opts.insertMode == true) shiftR(p, maskL, c); else setBufferElement(buffer, p, c);
  671. var next = seekNext(buffer, p);
  672. writeBuffer(input, buffer, next);
  673. if (opts.oncomplete && next == maskL)
  674. opts.oncomplete.call(input);
  675. } else if (android) writeBuffer(input, buffer, pos.begin);
  676. }
  677. return false;
  678. }
  679. }
  680. }
  681. }
  682. };
  683. }
  684. })(jQuery);