jquery.inputmask.js 53 KB

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