jquery.inputmask.js 56 KB

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