jquery.inputmask.js 57 KB

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