jquery.inputmask.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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.8d
  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: { 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,
  53. 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
  54. },
  55. ignorables: [8, 9, 13, 16, 17, 18, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 46, 91, 93, 108]
  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 || pos; //set new position from isValid
  396. c = 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. ignorable = false,
  546. lastPosition = -1,
  547. firstMaskPos = seekNext(buffer, -1),
  548. lastMaskPos = seekPrevious(buffer, getMaskLength()),
  549. isRTL = false;
  550. if (el.dir == "rtl" || opts.numericInput) {
  551. el.dir = "ltr"
  552. $input.css("text-align", "right");
  553. $input.removeAttr("dir");
  554. var inputData = $input.data('inputmask');
  555. inputData['isRTL'] = true;
  556. $input.data('inputmask', inputData);
  557. isRTL = true;
  558. }
  559. //unbind all events - to make sure that no other mask will interfere when re-masking
  560. $input.unbind(".inputmask");
  561. $input.removeClass('focus.inputmask');
  562. //bind events
  563. $input.bind("mouseenter.inputmask", function () {
  564. var $input = $(this), input = this;
  565. if (!$input.hasClass('focus.inputmask') && opts.showMaskOnHover) {
  566. var nptL = input._valueGet().length;
  567. if (nptL < buffer.length) {
  568. if (nptL == 0)
  569. buffer = _buffer.slice();
  570. writeBuffer(input, buffer);
  571. }
  572. }
  573. }).bind("blur.inputmask", function () {
  574. var $input = $(this), input = this, nptValue = input._valueGet();
  575. $input.removeClass('focus.inputmask');
  576. if (nptValue != undoBuffer) {
  577. $input.change();
  578. }
  579. if (opts.clearMaskOnLostFocus && nptValue != '') {
  580. if (nptValue == _buffer.join(''))
  581. input._valueSet('');
  582. else { //clearout optional tail of the mask
  583. clearOptionalTail(input, buffer);
  584. }
  585. }
  586. if (!isComplete(input)) {
  587. $input.trigger("incomplete");
  588. if (opts.clearIncomplete) {
  589. if (opts.clearMaskOnLostFocus)
  590. input._valueSet('');
  591. else {
  592. buffer = _buffer.slice();
  593. writeBuffer(input, buffer);
  594. }
  595. }
  596. }
  597. }).bind("focus.inputmask", function () {
  598. var $input = $(this), input = this, nptValue = input._valueGet();
  599. if (!$input.hasClass('focus.inputmask') && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  600. var nptL = nptValue.length;
  601. if (nptL < buffer.length) {
  602. if (nptL == 0)
  603. buffer = _buffer.slice();
  604. caret(input, checkVal(input, buffer, true));
  605. }
  606. }
  607. $input.addClass('focus.inputmask');
  608. undoBuffer = input._valueGet();
  609. }).bind("mouseleave.inputmask", function () {
  610. var $input = $(this), input = this;
  611. if (opts.clearMaskOnLostFocus) {
  612. if (!$input.hasClass('focus.inputmask')) {
  613. if (input._valueGet() == _buffer.join('') || input._valueGet() == '')
  614. input._valueSet('');
  615. else { //clearout optional tail of the mask
  616. clearOptionalTail(input, buffer);
  617. }
  618. }
  619. }
  620. }).bind("click.inputmask", function () {
  621. var input = this;
  622. setTimeout(function () {
  623. var selectedCaret = caret(input);
  624. if (selectedCaret.begin == selectedCaret.end) {
  625. var clickPosition = selectedCaret.begin;
  626. lastPosition = checkVal(input, buffer, false);
  627. if (isRTL)
  628. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  629. else
  630. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  631. }
  632. }, 0);
  633. }).bind('dblclick.inputmask', function () {
  634. var input = this;
  635. setTimeout(function () {
  636. caret(input, 0, lastPosition);
  637. }, 0);
  638. }).bind("keydown.inputmask", keydownEvent
  639. ).bind("keypress.inputmask", keypressEvent
  640. ).bind("keyup.inputmask", keyupEvent
  641. ).bind(pasteEvent + ".inputmask dragdrop.inputmask drop.inputmask", function () {
  642. var input = this;
  643. setTimeout(function () {
  644. caret(input, checkVal(input, buffer, true));
  645. }, 0);
  646. }).bind('setvalue.inputmask', function () {
  647. var input = this;
  648. undoBuffer = input._valueGet();
  649. checkVal(input, buffer, true);
  650. if (input._valueGet() == _buffer.join(''))
  651. input._valueSet('');
  652. }).bind('complete.inputmask', opts.oncomplete)
  653. .bind('incomplete.inputmask', opts.onincomplete)
  654. .bind('cleared.inputmask', opts.oncleared);
  655. //apply mask
  656. lastPosition = checkVal(el, buffer, true);
  657. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  658. var activeElement;
  659. try {
  660. activeElement = document.activeElement;
  661. } catch (e) { }
  662. if (activeElement === el) { //position the caret when in focus
  663. $input.addClass('focus.inputmask');
  664. caret(el, lastPosition);
  665. } else if (opts.clearMaskOnLostFocus) {
  666. if (el._valueGet() == _buffer.join('')) {
  667. el._valueSet('');
  668. } else {
  669. clearOptionalTail(el, buffer);
  670. }
  671. }
  672. installEventRuler(el);
  673. //private functions
  674. function installEventRuler(npt) {
  675. var events = $._data(npt).events;
  676. $.each(events, function (eventType, eventHandlers) {
  677. $.each(eventHandlers, function (ndx, eventHandler) {
  678. if (eventHandler.namespace == "inputmask") {
  679. var handler = eventHandler.handler;
  680. eventHandler.handler = function () {
  681. if (this.readOnly || this.disabled)
  682. return false;
  683. return handler.apply(this, arguments);
  684. };
  685. }
  686. });
  687. });
  688. }
  689. function patchValueProperty(npt) {
  690. var valueProperty;
  691. if (Object.getOwnPropertyDescriptor)
  692. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  693. if (valueProperty && valueProperty.get) {
  694. if (!npt._valueGet) {
  695. npt._valueGet = valueProperty.get;
  696. npt._valueSet = valueProperty.set;
  697. Object.defineProperty(npt, "value", {
  698. get: function () {
  699. var $self = $(this), inputData = $(this).data('inputmask');
  700. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  701. },
  702. set: function (value) {
  703. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  704. }
  705. });
  706. }
  707. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  708. if (!npt._valueGet) {
  709. npt._valueGet = npt.__lookupGetter__("value");
  710. npt._valueSet = npt.__lookupSetter__("value");
  711. npt.__defineGetter__("value", function () {
  712. var $self = $(this), inputData = $(this).data('inputmask');
  713. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  714. });
  715. npt.__defineSetter__("value", function (value) {
  716. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  717. });
  718. }
  719. } else {
  720. if (!npt._valueGet) {
  721. npt._valueGet = function () { return this.value; }
  722. npt._valueSet = function (value) { this.value = value; }
  723. }
  724. if ($.fn.val.inputmaskpatch != true) {
  725. $.fn.val = function () {
  726. if (arguments.length == 0) {
  727. var $self = $(this);
  728. if ($self.data('inputmask')) {
  729. if ($self.data('inputmask')['autoUnmask'])
  730. return $self.inputmask('unmaskedvalue');
  731. else {
  732. var result = $.inputmask.val.apply($self);
  733. return result != $self.data('inputmask')['_buffer'].join('') ? result : '';
  734. }
  735. } else return $.inputmask.val.apply($self);
  736. } else {
  737. var args = arguments;
  738. return this.each(function () {
  739. var $self = $(this);
  740. var result = $.inputmask.val.apply($self, args);
  741. if ($self.data('inputmask')) $self.triggerHandler('setvalue.inputmask');
  742. return result;
  743. });
  744. }
  745. };
  746. $.extend($.fn.val, {
  747. inputmaskpatch: true
  748. });
  749. }
  750. }
  751. }
  752. //shift chars to left from start to end and put c at end position if defined
  753. function shiftL(start, end, c) {
  754. while (!isMask(start) && start - 1 >= 0) start--;
  755. for (var i = start; i < end && i < getMaskLength(); i++) {
  756. if (isMask(i)) {
  757. setReTargetPlaceHolder(buffer, i);
  758. var j = seekNext(buffer, i);
  759. var p = getBufferElement(buffer, j);
  760. if (p != getPlaceHolder(j)) {
  761. if (j < getMaskLength() && isValid(i, p, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def) {
  762. setBufferElement(buffer, i, getBufferElement(buffer, j));
  763. setReTargetPlaceHolder(buffer, j); //cleanup next position
  764. } else {
  765. if (isMask(i))
  766. break;
  767. }
  768. } else if (c == undefined) break;
  769. } else {
  770. setReTargetPlaceHolder(buffer, i);
  771. }
  772. }
  773. if (c != undefined)
  774. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  775. buffer = truncateInput(buffer.join(''), isRTL).split('');
  776. if (buffer.length == 0) buffer = _buffer.slice();
  777. return start; //return the used start position
  778. }
  779. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  780. for (var i = start; i <= end && i < getMaskLength(); i++) {
  781. if (isMask(i)) {
  782. var t = getBufferElement(buffer, i);
  783. setBufferElement(buffer, i, c);
  784. if (t != getPlaceHolder(i)) {
  785. var j = seekNext(buffer, i);
  786. if (j < getMaskLength()) {
  787. if (isValid(j, t, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def)
  788. c = t;
  789. else {
  790. if (isMask(j))
  791. break;
  792. else c = t;
  793. }
  794. } else break;
  795. } else if (full !== true) break;
  796. } else
  797. setReTargetPlaceHolder(buffer, i);
  798. }
  799. var lengthBefore = buffer.length;
  800. buffer = truncateInput(buffer.join(''), isRTL).split('');
  801. if (buffer.length == 0) buffer = _buffer.slice();
  802. return end - (lengthBefore - buffer.length); //return new start position
  803. };
  804. function keydownEvent(e) {
  805. //Safari 5.1.x - modal dialog fires keypress twice workaround
  806. skipKeyPressEvent = false;
  807. var input = this, k = e.keyCode, pos = caret(input);
  808. //set input direction according the position to the radixPoint
  809. if (opts.numericInput) {
  810. var nptStr = input._valueGet();
  811. var radixPosition = nptStr.indexOf(opts.radixPoint);
  812. if (radixPosition != -1) {
  813. isRTL = pos.begin <= radixPosition || pos.end <= radixPosition;
  814. }
  815. }
  816. //backspace, delete, and escape get special treatment
  817. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  818. var maskL = getMaskLength();
  819. if (pos.begin == 0 && pos.end == maskL) {
  820. buffer = _buffer.slice();
  821. writeBuffer(input, buffer);
  822. caret(input, checkVal(input, buffer, false));
  823. } else if ((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) {
  824. clearBuffer(buffer, pos.begin, pos.end);
  825. writeBuffer(input, buffer, 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. return false;
  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. return false;
  853. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  854. caret(input, 0, e.shiftKey ? pos.begin : 0);
  855. return false;
  856. }
  857. else if (k == opts.keyCode.ESCAPE) {//escape
  858. input._valueSet(undoBuffer);
  859. caret(input, 0, checkVal(input, buffer));
  860. return false;
  861. } else if (k == opts.keyCode.INSERT) {//insert
  862. opts.insertMode = !opts.insertMode;
  863. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  864. return false;
  865. } else if (e.ctrlKey && k == 88) {
  866. setTimeout(function () {
  867. caret(input, checkVal(input, buffer, true));
  868. }, 0);
  869. } else if (!opts.insertMode) { //overwritemode
  870. if (k == opts.keyCode.RIGHT) {//right
  871. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  872. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  873. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  874. return false;
  875. } else if (k == opts.keyCode.LEFT) {//left
  876. var caretPos = pos.begin - 1;
  877. caretPos = caretPos > 0 ? caretPos : 0;
  878. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  879. return false;
  880. }
  881. }
  882. opts.onKeyDown.call(this, e, opts); //extra stuff to execute on keydown
  883. ignorable = $.inArray(k, opts.ignorables) != -1;
  884. }
  885. function keypressEvent(e) {
  886. //Safari 5.1.x - modal dialog fires keypress twice workaround
  887. if (skipKeyPressEvent) return false;
  888. skipKeyPressEvent = true;
  889. var input = this, $input = $(input);
  890. e = e || window.event;
  891. var k = e.which || e.charCode || e.keyCode,
  892. c = String.fromCharCode(k);
  893. if (opts.numericInput && c == opts.radixPoint) {
  894. var nptStr = input._valueGet();
  895. var radixPosition = nptStr.indexOf(opts.radixPoint);
  896. caret(input, seekNext(buffer, radixPosition != -1 ? radixPosition : getMaskLength()));
  897. }
  898. if (e.ctrlKey || e.altKey || e.metaKey || ignorable) {//Ignore
  899. return true;
  900. } else {
  901. if (k) {
  902. $input.trigger('input');
  903. var pos = caret(input), maskL = getMaskLength();
  904. clearBuffer(buffer, pos.begin, pos.end);
  905. if (isRTL) {
  906. var p = opts.numericInput ? pos.end : seekPrevious(buffer, pos.end), np;
  907. if ((np = isValid(p == maskL || getBufferElement(buffer, p) == opts.radixPoint ? seekPrevious(buffer, p) : p, c, buffer, false)) !== false) {
  908. if (np !== true) {
  909. p = np.pos || pos; //set new position from isValid
  910. c = np.c || c; //set new char from isValid
  911. }
  912. var firstUnmaskedPosition = firstMaskPos;
  913. if (opts.insertMode == true) {
  914. if (opts.greedy == true) {
  915. var bfrClone = buffer.slice();
  916. while (getBufferElement(bfrClone, firstUnmaskedPosition, true) != getPlaceHolder(firstUnmaskedPosition) && firstUnmaskedPosition <= p) {
  917. firstUnmaskedPosition = firstUnmaskedPosition == maskL ? (maskL + 1) : seekNext(buffer, firstUnmaskedPosition);
  918. }
  919. }
  920. if (firstUnmaskedPosition <= p && (opts.greedy || buffer.length < maskL)) {
  921. if (buffer[firstMaskPos] != getPlaceHolder(firstMaskPos) && buffer.length < maskL) {
  922. var offset = prepareBuffer(buffer, -1, isRTL);
  923. if (pos.end != 0) p = p + offset;
  924. maskL = buffer.length;
  925. }
  926. shiftL(firstUnmaskedPosition, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  927. } else return false;
  928. } else setBufferElement(buffer, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  929. writeBuffer(input, buffer, opts.numericInput && p == 0 ? seekNext(buffer, p) : p);
  930. setTimeout(function () { //timeout needed for IE
  931. if (isComplete(input))
  932. $input.trigger("complete");
  933. }, 0);
  934. } else if (android) writeBuffer(input, buffer, pos.begin);
  935. }
  936. else {
  937. var p = seekNext(buffer, pos.begin - 1), np;
  938. prepareBuffer(buffer, p, isRTL);
  939. if ((np = isValid(p, c, buffer, false)) !== false) {
  940. if (np !== true) {
  941. p = np.pos || p; //set new position from isValid
  942. c = np.c || c; //set new char from isValid
  943. }
  944. if (opts.insertMode == true) {
  945. var lastUnmaskedPosition = getMaskLength();
  946. var bfrClone = buffer.slice();
  947. while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
  948. lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(buffer, lastUnmaskedPosition);
  949. }
  950. if (lastUnmaskedPosition >= p)
  951. shiftR(p, buffer.length, c);
  952. else return false;
  953. }
  954. else setBufferElement(buffer, p, c);
  955. var next = seekNext(buffer, p);
  956. writeBuffer(input, buffer, next);
  957. setTimeout(function () { //timeout needed for IE
  958. if (isComplete(input))
  959. $input.trigger("complete");
  960. }, 0);
  961. } else if (android) writeBuffer(input, buffer, pos.begin);
  962. }
  963. return false;
  964. }
  965. }
  966. }
  967. function keyupEvent(e) {
  968. var $input = $(this), input = this;
  969. var k = e.keyCode;
  970. opts.onKeyUp.call(this, e, opts); //extra stuff to execute on keyup
  971. if (k == opts.keyCode.TAB && $input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  972. buffer = _buffer.slice();
  973. writeBuffer(input, buffer);
  974. if (!isRTL) caret(input, 0);
  975. undoBuffer = input._valueGet();
  976. }
  977. }
  978. }
  979. return this; //return this to expose publics
  980. };
  981. }
  982. })(jQuery);