jquery.inputmask.js 52 KB

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