jquery.inputmask.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /**
  2. * @license Input Mask plugin for jquery
  3. * http://github.com/RobinHerbots/jquery.inputmask
  4. * Copyright (c) 2010 - 2013 Robin Herbots
  5. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. * Version: 0.0.0
  7. */
  8. (function ($) {
  9. if ($.fn.inputmask == undefined) {
  10. $.inputmask = {
  11. //options default
  12. defaults: {
  13. placeholder: "_",
  14. optionalmarker: {
  15. start: "[",
  16. end: "]"
  17. },
  18. escapeChar: "\\",
  19. mask: null,
  20. oncomplete: $.noop, //executes when the mask is complete
  21. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  22. oncleared: $.noop, //executes when the mask is cleared
  23. repeat: 0, //repetitions of the mask
  24. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  25. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  26. clearMaskOnLostFocus: true,
  27. insertMode: true, //insert the input or overwrite the input
  28. clearIncomplete: false, //clear the incomplete input on blur
  29. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  30. onKeyUp: $.noop, //override to implement autocomplete on certain keys for example
  31. onKeyDown: $.noop, //override to implement autocomplete on certain keys for example
  32. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  33. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  34. onKeyValidation: $.noop, //executes on every key-press with the result of isValid
  35. //numeric basic properties
  36. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  37. radixPoint: "", //".", // | ","
  38. //numeric basic properties
  39. definitions: {
  40. '9': {
  41. validator: "[0-9]",
  42. cardinality: 1
  43. },
  44. 'a': {
  45. validator: "[A-Za-z\u0410-\u044F\u0401\u0451]",
  46. cardinality: 1
  47. },
  48. '*': {
  49. validator: "[A-Za-z\u0410-\u044F\u0401\u04510-9]",
  50. cardinality: 1
  51. }
  52. },
  53. keyCode: {
  54. 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,
  55. 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
  56. },
  57. //specify keycodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  58. ignorables: [9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123],
  59. getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) {
  60. var calculatedLength = buffer.length;
  61. if (!greedy && repeat > 1) {
  62. calculatedLength += (buffer.length * (repeat - 1));
  63. }
  64. return calculatedLength;
  65. }
  66. },
  67. val: $.fn.val, //store the original jquery val function
  68. escapeRegex: function (str) {
  69. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  70. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  71. }
  72. };
  73. $.fn.inputmask = function (fn, options) {
  74. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  75. var pasteEvent = isInputEventSupported('paste') ? 'paste' : 'input';
  76. var iphone = navigator.userAgent.match(/iphone/i) != null;
  77. var android = navigator.userAgent.match(/android.*safari.*/i) != null,
  78. android534;
  79. if (android) {
  80. var browser = navigator.userAgent.match(/safari.*/i);
  81. var version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  82. android = (version <= 533);
  83. android534 = (533 < version <= 534);
  84. }
  85. var caretposCorrection = null;
  86. if (typeof fn == "string") {
  87. switch (fn) {
  88. case "mask":
  89. //resolve possible aliases given by options
  90. resolveAlias(opts.alias, options);
  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 "remove":
  107. var tests, _buffer;
  108. return this.each(function () {
  109. var $input = $(this), input = this;
  110. setTimeout(function () {
  111. if ($input.data('inputmask')) {
  112. tests = $input.data('inputmask')['tests'];
  113. _buffer = $input.data('inputmask')['_buffer'];
  114. opts.greedy = $input.data('inputmask')['greedy'];
  115. opts.repeat = $input.data('inputmask')['repeat'];
  116. opts.definitions = $input.data('inputmask')['definitions'];
  117. //writeout the unmaskedvalue
  118. input._valueSet(unmaskedvalue($input, true));
  119. //clear data
  120. $input.removeData('inputmask');
  121. //unbind all events
  122. $input.unbind(".inputmask");
  123. $input.removeClass('focus.inputmask');
  124. //restore the value property
  125. var valueProperty;
  126. if (Object.getOwnPropertyDescriptor)
  127. valueProperty = Object.getOwnPropertyDescriptor(input, "value");
  128. if (valueProperty && valueProperty.get) {
  129. if (input._valueGet) {
  130. Object.defineProperty(input, "value", {
  131. get: input._valueGet,
  132. set: input._valueSet
  133. });
  134. }
  135. } else if (document.__lookupGetter__ && input.__lookupGetter__("value")) {
  136. if (input._valueGet) {
  137. input.__defineGetter__("value", input._valueGet);
  138. input.__defineSetter__("value", input._valueSet);
  139. }
  140. }
  141. delete input._valueGet;
  142. delete input._valueSet;
  143. }
  144. }, 0);
  145. });
  146. break;
  147. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  148. if (this.data('inputmask'))
  149. return this.data('inputmask')['_buffer'].join('');
  150. else return "";
  151. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  152. return this.data('inputmask') ? !this.data('inputmask')['autoUnmask'] : false;
  153. case "isComplete":
  154. var tests = this.data('inputmask')['tests'];
  155. var _buffer = this.data('inputmask')['_buffer'];
  156. opts.greedy = this.data('inputmask')['greedy'];
  157. opts.repeat = this.data('inputmask')['repeat'];
  158. opts.definitions = this.data('inputmask')['definitions'];
  159. return isComplete(this[0]);
  160. default:
  161. //check if the fn is an alias
  162. if (!resolveAlias(fn, options)) {
  163. //maybe fn is a mask so we try
  164. //set mask
  165. opts.mask = fn;
  166. }
  167. //init buffer
  168. var _buffer = getMaskTemplate();
  169. var tests = getTestingChain();
  170. return this.each(function () {
  171. mask(this);
  172. });
  173. break;
  174. }
  175. } else if (typeof fn == "object") {
  176. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  177. resolveAlias(opts.alias, fn); //resolve aliases
  178. //init buffer
  179. var _buffer = getMaskTemplate();
  180. var tests = getTestingChain();
  181. return this.each(function () {
  182. mask(this);
  183. });
  184. } else if (fn == undefined) {
  185. //look for data-inputmask atribute - the attribute should only contain optipns
  186. return this.each(function () {
  187. var attrOptions = $(this).attr("data-inputmask");
  188. if (attrOptions && attrOptions != "") {
  189. try {
  190. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  191. var options = $.parseJSON("{" + attrOptions + "}");
  192. opts = $.extend(true, {}, $.inputmask.defaults, options);
  193. resolveAlias(opts.alias, options);
  194. opts.alias = undefined;
  195. $(this).inputmask(opts);
  196. } catch (ex) { } //need a more relax parseJSON
  197. }
  198. });
  199. }
  200. //helper functions
  201. function isInputEventSupported(eventName) {
  202. var el = document.createElement('input'),
  203. eventName = 'on' + eventName,
  204. isSupported = (eventName in el);
  205. if (!isSupported) {
  206. el.setAttribute(eventName, 'return;');
  207. isSupported = typeof el[eventName] == 'function';
  208. }
  209. el = null;
  210. return isSupported;
  211. }
  212. function resolveAlias(aliasStr, options) {
  213. var aliasDefinition = opts.aliases[aliasStr];
  214. if (aliasDefinition) {
  215. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias); //alias is another alias
  216. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  217. $.extend(true, opts, options); //reapply extra given options
  218. return true;
  219. }
  220. return false;
  221. }
  222. function getMaskTemplate() {
  223. var escaped = false, outCount = 0, mask = opts.mask.toString();
  224. if (mask.length == 1 && opts.greedy == false) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
  225. var singleMask = $.map(mask.split(""), function (element, index) {
  226. var outElem = [];
  227. if (element == opts.escapeChar) {
  228. escaped = true;
  229. }
  230. else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
  231. var maskdef = opts.definitions[element];
  232. if (maskdef && !escaped) {
  233. for (var i = 0; i < maskdef.cardinality; i++) {
  234. outElem.push(getPlaceHolder(outCount + i));
  235. }
  236. } else {
  237. outElem.push(element);
  238. escaped = false;
  239. }
  240. outCount += outElem.length;
  241. return outElem;
  242. }
  243. });
  244. //allocate repetitions
  245. var repeatedMask = singleMask.slice();
  246. for (var i = 1; i < opts.repeat && opts.greedy; i++) {
  247. repeatedMask = repeatedMask.concat(singleMask.slice());
  248. }
  249. return repeatedMask;
  250. }
  251. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, offset: int, casing: null/upper/lower, def: definitionSymbol}
  252. function getTestingChain() {
  253. var isOptional = false, escaped = false, mask = opts.mask.toString();
  254. var newBlockMarker = false; //indicates wheter the begin/ending of a block should be indicated
  255. return $.map(mask.split(""), function (element, index) {
  256. var outElem = [];
  257. if (element == opts.escapeChar) {
  258. escaped = true;
  259. } else if (element == opts.optionalmarker.start && !escaped) {
  260. isOptional = true;
  261. newBlockMarker = true;
  262. }
  263. else if (element == opts.optionalmarker.end && !escaped) {
  264. isOptional = false;
  265. newBlockMarker = true;
  266. }
  267. else {
  268. var maskdef = opts.definitions[element];
  269. if (maskdef && !escaped) {
  270. var prevalidators = maskdef["prevalidator"], prevalidatorsL = prevalidators ? prevalidators.length : 0;
  271. for (var i = 1; i < maskdef.cardinality; i++) {
  272. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator["validator"], cardinality = prevalidator["cardinality"];
  273. 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"], def: element });
  274. if (isOptional == true) //reset newBlockMarker
  275. newBlockMarker = false;
  276. }
  277. 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"], def: element });
  278. } else {
  279. outElem.push({ fn: null, cardinality: 0, optionality: isOptional, newBlockMarker: newBlockMarker, offset: 0, casing: null, def: element });
  280. escaped = false;
  281. }
  282. //reset newBlockMarker
  283. newBlockMarker = false;
  284. return outElem;
  285. }
  286. });
  287. }
  288. function isValid(pos, c, buffer, strict) { //strict true ~ no correction or autofill
  289. var result = false;
  290. if (pos >= 0 && pos < getMaskLength(buffer)) {
  291. var testPos = determineTestPosition(pos), loopend = c ? 1 : 0, chrs = '';
  292. for (var i = tests[testPos].cardinality; i > loopend; i--) {
  293. chrs += getBufferElement(buffer, testPos - (i - 1));
  294. }
  295. if (c) {
  296. chrs += c;
  297. }
  298. //return is false or a json object => { pos: ??, c: ??}
  299. result = tests[testPos].fn != null ? tests[testPos].fn.test(chrs, buffer, pos, strict, opts) : false;
  300. }
  301. setTimeout(function () { opts.onKeyValidation.call(this, result, opts); }, 0); //extra stuff to execute on keydown
  302. return result;
  303. }
  304. function isMask(pos) {
  305. var testPos = determineTestPosition(pos);
  306. var test = tests[testPos];
  307. return test != undefined ? test.fn : false;
  308. }
  309. function determineTestPosition(pos) {
  310. return pos % tests.length;
  311. }
  312. function getPlaceHolder(pos) {
  313. return opts.placeholder.charAt(pos % opts.placeholder.length);
  314. }
  315. function getMaskLength(currentBuffer) {
  316. return opts.getMaskLength(_buffer, opts.greedy, opts.repeat, currentBuffer, opts);
  317. }
  318. //pos: from position
  319. function seekNext(buffer, pos) {
  320. var maskL = getMaskLength(buffer);
  321. if (pos >= maskL) return maskL;
  322. var position = pos;
  323. while (++position < maskL && !isMask(position)) { };
  324. return position;
  325. }
  326. //pos: from position
  327. function seekPrevious(buffer, pos) {
  328. var position = pos;
  329. if (position <= 0) return 0;
  330. while (--position > 0 && !isMask(position)) { };
  331. return position;
  332. }
  333. function setBufferElement(buffer, position, element) {
  334. //position = prepareBuffer(buffer, position);
  335. var test = tests[determineTestPosition(position)];
  336. var elem = element;
  337. if (elem != undefined) {
  338. switch (test.casing) {
  339. case "upper":
  340. elem = element.toUpperCase();
  341. break;
  342. case "lower":
  343. elem = element.toLowerCase();
  344. break;
  345. }
  346. }
  347. buffer[position] = elem;
  348. }
  349. function getBufferElement(buffer, position, autoPrepare) {
  350. if (autoPrepare) position = prepareBuffer(buffer, position);
  351. return buffer[position];
  352. }
  353. //needed to handle the non-greedy mask repetitions
  354. function prepareBuffer(buffer, position, isRTL) {
  355. var j;
  356. if (isRTL) {
  357. while (position < 0 && buffer.length < getMaskLength(buffer)) {
  358. j = _buffer.length - 1;
  359. position = _buffer.length;
  360. while (_buffer[j] !== undefined) {
  361. buffer.unshift(_buffer[j--]);
  362. }
  363. }
  364. } else {
  365. while (buffer[position] == undefined && buffer.length < getMaskLength(buffer)) {
  366. j = 0;
  367. while (_buffer[j] !== undefined) { //add a new buffer
  368. buffer.push(_buffer[j++]);
  369. }
  370. }
  371. }
  372. return position;
  373. }
  374. function writeBuffer(input, buffer, caretPos) {
  375. input._valueSet(buffer.join(''));
  376. if (caretPos != undefined) {
  377. if (android) {
  378. setTimeout(function () {
  379. caret(input, caretPos);
  380. }, 100);
  381. }
  382. else caret(input, caretPos);
  383. }
  384. };
  385. function clearBuffer(buffer, start, end) {
  386. for (var i = start, maskL = getMaskLength(buffer) ; i < end && i < maskL; i++) {
  387. setBufferElement(buffer, i, getBufferElement(_buffer.slice(), i));
  388. }
  389. };
  390. function setReTargetPlaceHolder(buffer, pos) {
  391. var testPos = determineTestPosition(pos);
  392. setBufferElement(buffer, pos, getBufferElement(_buffer, testPos));
  393. }
  394. function checkVal(input, buffer, clearInvalid, skipRadixHandling) {
  395. var isRTL = $(input).data('inputmask')['isRTL'],
  396. inputValue = truncateInput(input._valueGet(), isRTL).split('');
  397. var maskL = getMaskLength(buffer);
  398. if (isRTL) { //align inputValue for RTL/numeric input
  399. var inputValueRev = inputValue.reverse(); inputValueRev.length = maskL;
  400. for (var i = 0; i < maskL; i++) {
  401. var targetPosition = determineTestPosition(maskL - (i + 1));
  402. if (tests[targetPosition].fn == null && inputValueRev[i] != getBufferElement(_buffer, targetPosition)) {
  403. inputValueRev.splice(i, 0, getBufferElement(_buffer, targetPosition));
  404. inputValueRev.length = maskL;
  405. } else {
  406. inputValueRev[i] = inputValueRev[i] || getBufferElement(_buffer, targetPosition);
  407. }
  408. }
  409. inputValue = inputValueRev.reverse();
  410. }
  411. clearBuffer(buffer, 0, buffer.length);
  412. buffer.length = _buffer.length;
  413. var lastMatch = -1, checkPosition = -1, np, ivl = inputValue.length, rtlMatch = ivl == 0 ? maskL : -1;
  414. for (var i = 0; i < ivl; i++) {
  415. for (var pos = checkPosition + 1; pos < maskL; pos++) {
  416. if (isMask(pos)) {
  417. var c = inputValue[i];
  418. if ((np = isValid(pos, c, buffer, !clearInvalid)) !== false) {
  419. if (np !== true) {
  420. pos = np.pos != undefined ? np.pos : pos; //set new position from isValid
  421. c = np.c != undefined ? np.c : c; //set new char from isValid
  422. }
  423. setBufferElement(buffer, pos, c);
  424. lastMatch = checkPosition = pos;
  425. } else {
  426. setReTargetPlaceHolder(buffer, pos);
  427. if (c == getPlaceHolder(pos)) {
  428. checkPosition = pos;
  429. rtlMatch = pos;
  430. }
  431. }
  432. break;
  433. } else { //nonmask
  434. setReTargetPlaceHolder(buffer, pos);
  435. if (lastMatch == checkPosition) //once outsync the nonmask cannot be the lastmatch
  436. lastMatch = pos;
  437. checkPosition = pos;
  438. if (inputValue[i] == getBufferElement(buffer, pos))
  439. break;
  440. }
  441. }
  442. }
  443. //Truncate buffer when using non-greedy masks
  444. if (opts.greedy == false) {
  445. var newBuffer = truncateInput(buffer.join(''), isRTL).split('');
  446. while (buffer.length != newBuffer.length) { //map changes into the original buffer
  447. isRTL ? buffer.shift() : buffer.pop();
  448. }
  449. }
  450. if (clearInvalid) {
  451. writeBuffer(input, buffer);
  452. }
  453. return isRTL ? (opts.numericInput ? (opts.radixPoint != "" && $.inArray(opts.radixPoint, buffer) != -1 && skipRadixHandling !== true ? $.inArray(opts.radixPoint, buffer) : seekNext(buffer, maskL)) : seekNext(buffer, rtlMatch)) : seekNext(buffer, lastMatch);
  454. }
  455. function escapeRegex(str) {
  456. return $.inputmask.escapeRegex.call(this, str);
  457. }
  458. function truncateInput(inputValue, rtl) {
  459. return rtl ? inputValue.replace(new RegExp("^(" + escapeRegex(_buffer.join('')) + ")*"), "") : inputValue.replace(new RegExp("(" + escapeRegex(_buffer.join('')) + ")*$"), "");
  460. }
  461. function clearOptionalTail(input, buffer) {
  462. checkVal(input, buffer, false);
  463. var tmpBuffer = buffer.slice(), testPos, pos;
  464. if ($(input).data('inputmask')['isRTL']) {
  465. for (pos = 0; pos <= tmpBuffer.length - 1; pos++) {
  466. testPos = determineTestPosition(pos);
  467. if (tests[testPos].optionality) {
  468. if (!isMask(pos) || !isValid(pos, buffer[pos], buffer, true))
  469. tmpBuffer.splice(0, 1);
  470. else break;
  471. } else break;
  472. }
  473. } else {
  474. for (pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  475. testPos = determineTestPosition(pos);
  476. if (tests[testPos].optionality) {
  477. if (!isMask(pos) || !isValid(pos, buffer[pos], buffer, true))
  478. tmpBuffer.pop();
  479. else break;
  480. } else break;
  481. }
  482. }
  483. writeBuffer(input, tmpBuffer);
  484. }
  485. //functionality fn
  486. function unmaskedvalue($input, skipDatepickerCheck) {
  487. var input = $input[0];
  488. if (tests && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  489. var buffer = _buffer.slice();
  490. checkVal(input, buffer);
  491. return $.map(buffer, function (element, index) {
  492. return isMask(index) && isValid(index, element, buffer, true) ? element : null;
  493. }).join('');
  494. }
  495. else {
  496. return input._valueGet();
  497. }
  498. }
  499. function caret(input, begin, end) {
  500. var npt = input.jquery && input.length > 0 ? input[0] : input;
  501. if (typeof begin == 'number') {
  502. if (!$(input).is(':visible')) {
  503. return;
  504. }
  505. end = (typeof end == 'number') ? end : begin;
  506. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  507. if (npt.setSelectionRange) {
  508. if (end == begin) {
  509. npt.focus();
  510. npt.setSelectionRange(begin, end);
  511. } else {
  512. npt.select();
  513. npt.selectionStart = begin;
  514. npt.selectionEnd = android534 ? begin : end;
  515. }
  516. } else if (npt.createTextRange) {
  517. var range = npt.createTextRange();
  518. range.collapse(true);
  519. range.moveEnd('character', end);
  520. range.moveStart('character', begin);
  521. range.select();
  522. }
  523. npt.focus();
  524. if (android && end != npt.selectionEnd) caretposCorrection = { begin: begin, end: end };
  525. } else {
  526. if (!$(input).is(':visible')) {
  527. return { begin: 0, end: 0 };
  528. }
  529. var caretpos = android ? caretposCorrection : null, caretposCorrection = null;
  530. if (caretpos == null) {
  531. if (npt.setSelectionRange) {
  532. begin = npt.selectionStart;
  533. end = npt.selectionEnd;
  534. } else if (document.selection && document.selection.createRange) {
  535. var range = document.selection.createRange();
  536. begin = 0 - range.duplicate().moveStart('character', -100000);
  537. end = begin + range.text.length;
  538. }
  539. caretpos = { begin: begin, end: end };
  540. }
  541. return caretpos;
  542. }
  543. };
  544. function isComplete(npt) {
  545. var complete = true, nptValue = npt._valueGet(), ml = nptValue.length;
  546. for (var i = 0; i < ml; i++) {
  547. if (isMask(i) && nptValue.charAt(i) == getPlaceHolder(i)) {
  548. complete = false;
  549. break;
  550. }
  551. }
  552. return complete;
  553. }
  554. function mask(el) {
  555. var $input = $(el);
  556. if (!$input.is(":input")) return;
  557. var buffer = _buffer.slice();
  558. //correct greedy setting if needed
  559. opts.greedy = opts.greedy ? opts.greedy : opts.repeat == 0;
  560. //handle maxlength attribute
  561. var maxLength = $input.prop('maxLength');
  562. if (getMaskLength(buffer) > maxLength && maxLength > -1) { //FF sets no defined max length to -1
  563. if (maxLength < _buffer.length) _buffer.length = maxLength;
  564. if (opts.greedy == false) {
  565. opts.repeat = Math.round(maxLength / _buffer.length);
  566. }
  567. $input.prop('maxLength', getMaskLength(buffer) * 2);
  568. }
  569. //store tests & original buffer in the input element - used to get the unmasked value
  570. $input.data('inputmask', {
  571. 'tests': tests,
  572. '_buffer': _buffer,
  573. 'greedy': opts.greedy,
  574. 'repeat': opts.repeat,
  575. 'autoUnmask': opts.autoUnmask,
  576. 'definitions': opts.definitions,
  577. 'isRTL': false
  578. });
  579. patchValueProperty(el);
  580. //init vars
  581. var undoBuffer = el._valueGet(),
  582. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  583. ignorable = false,
  584. lastPosition = -1,
  585. firstMaskPos = seekNext(buffer, -1),
  586. lastMaskPos = seekPrevious(buffer, getMaskLength(buffer)),
  587. isRTL = false;
  588. if (el.dir == "rtl" || opts.numericInput) {
  589. el.dir = "ltr"
  590. $input.css("text-align", "right");
  591. $input.removeAttr("dir");
  592. var inputData = $input.data('inputmask');
  593. inputData['isRTL'] = true;
  594. $input.data('inputmask', inputData);
  595. isRTL = true;
  596. }
  597. //unbind all events - to make sure that no other mask will interfere when re-masking
  598. $input.unbind(".inputmask");
  599. $input.removeClass('focus.inputmask');
  600. //bind events
  601. $input.bind("mouseenter.inputmask", function () {
  602. var $input = $(this), input = this;
  603. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  604. var nptL = input._valueGet().length;
  605. if (nptL < buffer.length) {
  606. if (nptL == 0)
  607. buffer = _buffer.slice();
  608. writeBuffer(input, buffer);
  609. }
  610. }
  611. }).bind("blur.inputmask", function () {
  612. var $input = $(this), input = this, nptValue = input._valueGet();
  613. $input.removeClass('focus.inputmask');
  614. if (nptValue != undoBuffer) {
  615. $input.change();
  616. }
  617. if (opts.clearMaskOnLostFocus && nptValue != '') {
  618. if (nptValue == _buffer.join(''))
  619. input._valueSet('');
  620. else { //clearout optional tail of the mask
  621. clearOptionalTail(input, buffer);
  622. }
  623. }
  624. if (!isComplete(input)) {
  625. $input.trigger("incomplete");
  626. if (opts.clearIncomplete) {
  627. if (opts.clearMaskOnLostFocus)
  628. input._valueSet('');
  629. else {
  630. buffer = _buffer.slice();
  631. writeBuffer(input, buffer);
  632. }
  633. }
  634. }
  635. }).bind("focus.inputmask", function () {
  636. var $input = $(this), input = this, nptValue = input._valueGet();
  637. if (opts.showMaskOnFocus && !$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  638. var nptL = nptValue.length;
  639. if (nptL < buffer.length) {
  640. if (nptL == 0)
  641. buffer = _buffer.slice();
  642. caret(input, checkVal(input, buffer, true));
  643. }
  644. }
  645. $input.addClass('focus.inputmask');
  646. undoBuffer = input._valueGet();
  647. }).bind("mouseleave.inputmask", function () {
  648. var $input = $(this), input = this;
  649. if (opts.clearMaskOnLostFocus) {
  650. if (!$input.hasClass('focus.inputmask')) {
  651. if (input._valueGet() == _buffer.join('') || input._valueGet() == '')
  652. input._valueSet('');
  653. else { //clearout optional tail of the mask
  654. clearOptionalTail(input, buffer);
  655. }
  656. }
  657. }
  658. }).bind("click.inputmask", function () {
  659. var input = this;
  660. setTimeout(function () {
  661. var selectedCaret = caret(input);
  662. if (selectedCaret.begin == selectedCaret.end) {
  663. var clickPosition = selectedCaret.begin;
  664. lastPosition = checkVal(input, buffer, false);
  665. determineInputDirection(input, selectedCaret);
  666. if (isRTL)
  667. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  668. else
  669. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  670. }
  671. }, 0);
  672. }).bind('dblclick.inputmask', function () {
  673. var input = this;
  674. setTimeout(function () {
  675. caret(input, 0, lastPosition);
  676. }, 0);
  677. }).bind("keydown.inputmask", keydownEvent
  678. ).bind("keypress.inputmask", keypressEvent
  679. ).bind("keyup.inputmask", keyupEvent
  680. ).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function () {
  681. var input = this;
  682. setTimeout(function () {
  683. caret(input, checkVal(input, buffer, true));
  684. }, 0);
  685. }).bind('setvalue.inputmask', function () {
  686. var input = this;
  687. undoBuffer = input._valueGet();
  688. checkVal(input, buffer, true);
  689. if (input._valueGet() == _buffer.join(''))
  690. input._valueSet('');
  691. }).bind('complete.inputmask', opts.oncomplete)
  692. .bind('incomplete.inputmask', opts.onincomplete)
  693. .bind('cleared.inputmask', opts.oncleared);
  694. //apply mask
  695. lastPosition = checkVal(el, buffer, true);
  696. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  697. var activeElement;
  698. try {
  699. activeElement = document.activeElement;
  700. } catch (e) { }
  701. if (activeElement === el) { //position the caret when in focus
  702. $input.addClass('focus.inputmask');
  703. caret(el, lastPosition);
  704. } else if (opts.clearMaskOnLostFocus) {
  705. if (el._valueGet() == _buffer.join('')) {
  706. el._valueSet('');
  707. } else {
  708. clearOptionalTail(el, buffer);
  709. }
  710. }
  711. installEventRuler(el);
  712. //private functions
  713. function installEventRuler(npt) {
  714. var events = $._data(npt).events;
  715. $.each(events, function (eventType, eventHandlers) {
  716. $.each(eventHandlers, function (ndx, eventHandler) {
  717. if (eventHandler.namespace == "inputmask") {
  718. var handler = eventHandler.handler;
  719. eventHandler.handler = function () {
  720. if (this.readOnly || this.disabled)
  721. return false;
  722. return handler.apply(this, arguments);
  723. };
  724. }
  725. });
  726. });
  727. }
  728. function patchValueProperty(npt) {
  729. var valueProperty;
  730. if (Object.getOwnPropertyDescriptor)
  731. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  732. if (valueProperty && valueProperty.get) {
  733. if (!npt._valueGet) {
  734. npt._valueGet = valueProperty.get;
  735. npt._valueSet = valueProperty.set;
  736. Object.defineProperty(npt, "value", {
  737. get: function () {
  738. var $self = $(this), inputData = $(this).data('inputmask');
  739. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  740. },
  741. set: function (value) {
  742. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  743. }
  744. });
  745. }
  746. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  747. if (!npt._valueGet) {
  748. npt._valueGet = npt.__lookupGetter__("value");
  749. npt._valueSet = npt.__lookupSetter__("value");
  750. npt.__defineGetter__("value", function () {
  751. var $self = $(this), inputData = $(this).data('inputmask');
  752. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  753. });
  754. npt.__defineSetter__("value", function (value) {
  755. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  756. });
  757. }
  758. } else {
  759. if (!npt._valueGet) {
  760. npt._valueGet = function () { return this.value; }
  761. npt._valueSet = function (value) { this.value = value; }
  762. }
  763. if ($.fn.val.inputmaskpatch != true) {
  764. $.fn.val = function () {
  765. if (arguments.length == 0) {
  766. var $self = $(this);
  767. if ($self.data('inputmask')) {
  768. if ($self.data('inputmask')['autoUnmask'])
  769. return $self.inputmask('unmaskedvalue');
  770. else {
  771. var result = $.inputmask.val.apply($self);
  772. return result != $self.data('inputmask')['_buffer'].join('') ? result : '';
  773. }
  774. } else return $.inputmask.val.apply($self);
  775. } else {
  776. var args = arguments;
  777. return this.each(function () {
  778. var $self = $(this);
  779. var result = $.inputmask.val.apply($self, args);
  780. if ($self.data('inputmask')) $self.triggerHandler('setvalue.inputmask');
  781. return result;
  782. });
  783. }
  784. };
  785. $.extend($.fn.val, {
  786. inputmaskpatch: true
  787. });
  788. }
  789. }
  790. }
  791. function determineInputDirection(input, pos) {
  792. //set input direction according the position to the radixPoint
  793. if (opts.numericInput && opts.radixPoint != "") {
  794. var nptStr = input._valueGet();
  795. var radixPosition = nptStr.indexOf(opts.radixPoint);
  796. isRTL = pos.begin <= radixPosition || pos.end <= radixPosition || radixPosition == -1;
  797. }
  798. }
  799. //shift chars to left from start to end and put c at end position if defined
  800. function shiftL(start, end, c) {
  801. while (!isMask(start) && start - 1 >= 0) start--;
  802. for (var i = start; i < end && i < getMaskLength(buffer) ; i++) {
  803. if (isMask(i)) {
  804. setReTargetPlaceHolder(buffer, i);
  805. var j = seekNext(buffer, i);
  806. var p = getBufferElement(buffer, j);
  807. if (p != getPlaceHolder(j)) {
  808. if (j < getMaskLength(buffer) && isValid(i, p, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def) {
  809. setBufferElement(buffer, i, getBufferElement(buffer, j));
  810. setReTargetPlaceHolder(buffer, j); //cleanup next position
  811. } else {
  812. if (isMask(i))
  813. break;
  814. }
  815. } else if (c == undefined) break;
  816. } else {
  817. setReTargetPlaceHolder(buffer, i);
  818. }
  819. }
  820. if (c != undefined)
  821. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  822. buffer = truncateInput(buffer.join(''), isRTL).split('');
  823. if (buffer.length == 0) buffer = _buffer.slice();
  824. return start; //return the used start position
  825. }
  826. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  827. for (var i = start; i <= end && i < getMaskLength(buffer) ; i++) {
  828. if (isMask(i)) {
  829. var t = getBufferElement(buffer, i);
  830. setBufferElement(buffer, i, c);
  831. if (t != getPlaceHolder(i)) {
  832. var j = seekNext(buffer, i);
  833. if (j < getMaskLength(buffer)) {
  834. if (isValid(j, t, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def)
  835. c = t;
  836. else {
  837. if (isMask(j))
  838. break;
  839. else c = t;
  840. }
  841. } else break;
  842. } else if (full !== true) break;
  843. } else
  844. setReTargetPlaceHolder(buffer, i);
  845. }
  846. var lengthBefore = buffer.length;
  847. buffer = truncateInput(buffer.join(''), isRTL).split('');
  848. if (buffer.length == 0) buffer = _buffer.slice();
  849. return end - (lengthBefore - buffer.length); //return new start position
  850. };
  851. function keydownEvent(e) {
  852. //Safari 5.1.x - modal dialog fires keypress twice workaround
  853. skipKeyPressEvent = false;
  854. var input = this, k = e.keyCode, pos = caret(input);
  855. determineInputDirection(input, pos);
  856. //backspace, delete, and escape get special treatment
  857. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  858. var maskL = getMaskLength(buffer);
  859. if (pos.begin == 0 && pos.end == maskL) { //remove full selection
  860. buffer = _buffer.slice();
  861. writeBuffer(input, buffer);
  862. caret(input, checkVal(input, buffer, false));
  863. } else if ((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) { //partial selection
  864. clearBuffer(buffer, pos.begin, pos.end);
  865. writeBuffer(input, buffer);
  866. caret(isRTL ? checkVal(input, buffer, false) : pos.begin);
  867. } else { //handle delete
  868. var beginPos = pos.begin;
  869. if (k == opts.keyCode.DELETE) {
  870. if (beginPos < firstMaskPos)
  871. beginPos = firstMaskPos;
  872. if (beginPos < maskL) {
  873. if (opts.numericInput && opts.radixPoint != "" && buffer[beginPos] == opts.radixPoint) {
  874. beginPos = (buffer.length - 1 == beginPos) /* radixPoint is latest? delete it */ ? beginPos : seekNext(buffer, beginPos);
  875. beginPos = shiftL(beginPos, maskL);
  876. } else {
  877. if (isRTL) {
  878. beginPos = shiftR(firstMaskPos, beginPos, getPlaceHolder(beginPos), true);
  879. beginPos = seekNext(buffer, beginPos);
  880. } else {
  881. beginPos = shiftL(beginPos, maskL);
  882. }
  883. }
  884. writeBuffer(input, buffer, beginPos);
  885. }
  886. } else if (k == opts.keyCode.BACKSPACE) { //handle backspace
  887. if (beginPos > firstMaskPos) {
  888. beginPos -= 1;
  889. if (opts.numericInput && opts.radixPoint != "" && buffer[beginPos] == opts.radixPoint) {
  890. beginPos = shiftR(firstMaskPos, (buffer.length - 1 == beginPos) /* radixPoint is latest? delete it */ ? beginPos : beginPos - 1, getPlaceHolder(beginPos), true);
  891. beginPos++;
  892. } else {
  893. if (isRTL) {
  894. beginPos = shiftR(firstMaskPos, beginPos, getPlaceHolder(beginPos), true);
  895. beginPos = buffer[beginPos + 1] == opts.radixPoint ? beginPos + 1 : seekNext(buffer, beginPos);
  896. } else {
  897. beginPos = shiftL(beginPos, maskL);
  898. }
  899. }
  900. writeBuffer(input, buffer, beginPos);
  901. }
  902. }
  903. }
  904. if (input._valueGet() == _buffer.join(''))
  905. $(input).trigger('cleared');
  906. e.preventDefault(); //stop default action but allow propagation
  907. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  908. setTimeout(function () {
  909. var caretPos = checkVal(input, buffer, false, true);
  910. if (!opts.insertMode && caretPos == getMaskLength(buffer) && !e.shiftKey) caretPos--;
  911. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  912. }, 0);
  913. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  914. caret(input, 0, e.shiftKey ? pos.begin : 0);
  915. }
  916. else if (k == opts.keyCode.ESCAPE) {//escape
  917. input._valueSet(undoBuffer);
  918. caret(input, 0, checkVal(input, buffer));
  919. } else if (k == opts.keyCode.INSERT) {//insert
  920. opts.insertMode = !opts.insertMode;
  921. caret(input, !opts.insertMode && pos.begin == getMaskLength(buffer) ? pos.begin - 1 : pos.begin);
  922. } else if (e.ctrlKey && k == 88) {
  923. setTimeout(function () {
  924. caret(input, checkVal(input, buffer, true));
  925. }, 0);
  926. } else if (!opts.insertMode) { //overwritemode
  927. if (k == opts.keyCode.RIGHT) {//right
  928. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  929. caretPos = caretPos < getMaskLength(buffer) ? caretPos : pos.end;
  930. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  931. } else if (k == opts.keyCode.LEFT) {//left
  932. var caretPos = pos.begin - 1;
  933. caretPos = caretPos > 0 ? caretPos : 0;
  934. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  935. }
  936. }
  937. opts.onKeyDown.call(this, e, buffer, opts); //extra stuff to execute on keydown
  938. ignorable = $.inArray(k, opts.ignorables) != -1;
  939. }
  940. function keypressEvent(e) {
  941. //Safari 5.1.x - modal dialog fires keypress twice workaround
  942. if (skipKeyPressEvent) return false;
  943. skipKeyPressEvent = true;
  944. var input = this, $input = $(input);
  945. e = e || window.event;
  946. var k = e.which || e.charCode || e.keyCode,
  947. c = String.fromCharCode(k);
  948. if (opts.numericInput && c == opts.radixPoint) {
  949. var nptStr = input._valueGet();
  950. var radixPosition = nptStr.indexOf(opts.radixPoint);
  951. caret(input, seekNext(buffer, radixPosition != -1 ? radixPosition : getMaskLength(buffer)));
  952. }
  953. if (e.ctrlKey || e.altKey || e.metaKey || ignorable) {
  954. return true;
  955. } else {
  956. if (k) {
  957. $input.trigger('input');
  958. var pos = caret(input), maskL = getMaskLength(buffer), writeOutBuffer = true;
  959. clearBuffer(buffer, pos.begin, pos.end);
  960. if (isRTL) {
  961. var p = seekPrevious(buffer, pos.end), np;
  962. if ((np = isValid(p == maskL || getBufferElement(buffer, p) == opts.radixPoint ? seekPrevious(buffer, p) : p, c, buffer, false)) !== false) {
  963. if (np !== true) {
  964. p = np.pos != undefined ? np.pos : p; //set new position from isValid
  965. c = np.c != undefined ? np.c : c; //set new char from isValid
  966. }
  967. maskL = getMaskLength(buffer); //update masklength to include possible groupSeparator offset
  968. var firstUnmaskedPosition = firstMaskPos;
  969. if (opts.insertMode == true) {
  970. if (opts.greedy == true) {
  971. var bfrClone = buffer.slice();
  972. while (getBufferElement(bfrClone, firstUnmaskedPosition, true) != getPlaceHolder(firstUnmaskedPosition) && firstUnmaskedPosition <= p) {
  973. firstUnmaskedPosition = firstUnmaskedPosition == maskL ? (maskL + 1) : seekNext(buffer, firstUnmaskedPosition);
  974. }
  975. }
  976. if (firstUnmaskedPosition <= p && (opts.greedy || buffer.length < maskL)) {
  977. if (buffer[firstMaskPos] != getPlaceHolder(firstMaskPos) && buffer.length < maskL) {
  978. var offset = prepareBuffer(buffer, -1, isRTL);
  979. if (pos.end != 0) p = p + offset;
  980. maskL = buffer.length;
  981. }
  982. shiftL(firstUnmaskedPosition, p, c);
  983. } else writeOutBuffer = false;
  984. } else setBufferElement(buffer, p, c);
  985. if (writeOutBuffer) {
  986. writeBuffer(input, buffer, opts.numericInput ? p + 1 : p);
  987. setTimeout(function () { //timeout needed for IE
  988. if (isComplete(input))
  989. $input.trigger("complete");
  990. }, 0);
  991. }
  992. } else if (android) writeBuffer(input, buffer, pos.begin);
  993. }
  994. else {
  995. var p = seekNext(buffer, pos.begin - 1), np;
  996. prepareBuffer(buffer, p, isRTL);
  997. if ((np = isValid(p, c, buffer, false)) !== false) {
  998. if (np !== true) {
  999. p = np.pos != undefined ? np.pos : p; //set new position from isValid
  1000. c = np.c != undefined ? np.c : c; //set new char from isValid
  1001. }
  1002. if (opts.insertMode == true) {
  1003. var lastUnmaskedPosition = getMaskLength(buffer);
  1004. var bfrClone = buffer.slice();
  1005. while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
  1006. lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(buffer, lastUnmaskedPosition);
  1007. }
  1008. if (lastUnmaskedPosition >= p)
  1009. shiftR(p, buffer.length, c);
  1010. else writeOutBuffer = false;
  1011. }
  1012. else setBufferElement(buffer, p, c);
  1013. if (writeOutBuffer) {
  1014. var next = seekNext(buffer, p);
  1015. writeBuffer(input, buffer, next);
  1016. setTimeout(function () { //timeout needed for IE
  1017. if (isComplete(input))
  1018. $input.trigger("complete");
  1019. }, 0);
  1020. }
  1021. } else if (android) writeBuffer(input, buffer, pos.begin);
  1022. }
  1023. e.preventDefault();
  1024. }
  1025. }
  1026. }
  1027. function keyupEvent(e) {
  1028. var $input = $(this), input = this;
  1029. var k = e.keyCode;
  1030. opts.onKeyUp.call(this, e, buffer, opts); //extra stuff to execute on keyup
  1031. if (k == opts.keyCode.TAB && $input.hasClass('focus.inputmask') && input._valueGet().length == 0 && opts.showMaskOnFocus) {
  1032. buffer = _buffer.slice();
  1033. writeBuffer(input, buffer);
  1034. if (!isRTL) caret(input, 0);
  1035. undoBuffer = input._valueGet();
  1036. }
  1037. }
  1038. }
  1039. return this; //return this to expose publics
  1040. };
  1041. }
  1042. })(jQuery);