jquery.inputmask.js 55 KB

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