jquery.inputmask.js 54 KB

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