jquery.inputmask.js 53 KB

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