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