jquery.inputmask.js 53 KB

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