jquery.inputmask.js 55 KB

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