jquery.inputmask.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. //correct greedy setting if needed
  494. opts.greedy = opts.greedy ? opts.greedy : opts.repeat == 0;
  495. //handle maxlength attribute
  496. var maxLength = $input.prop('maxLength');
  497. if (getMaskLength() > maxLength && maxLength > -1) { //FF sets no defined max length to -1
  498. if (maxLength < _buffer.length) _buffer.length = maxLength;
  499. if (opts.greedy == false) {
  500. opts.repeat = Math.round(maxLength / _buffer.length);
  501. }
  502. }
  503. $input.prop('maxLength', getMaskLength() * 2);
  504. //store tests & original buffer in the input element - used to get the unmasked value
  505. $input.data('inputmask', {
  506. 'tests': tests,
  507. '_buffer': _buffer,
  508. 'greedy': opts.greedy,
  509. 'repeat': opts.repeat,
  510. 'autoUnmask': opts.autoUnmask,
  511. 'definitions': opts.definitions,
  512. 'isRTL': false
  513. });
  514. patchValueProperty(el);
  515. //init vars
  516. var buffer = _buffer.slice(),
  517. undoBuffer = el._valueGet(),
  518. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  519. ignorable = false,
  520. lastPosition = -1,
  521. firstMaskPos = seekNext(buffer, -1),
  522. lastMaskPos = seekPrevious(buffer, getMaskLength()),
  523. isRTL = false;
  524. if (el.dir == "rtl" || opts.numericInput) {
  525. el.dir = "ltr"
  526. $input.css("text-align", "right");
  527. $input.removeAttr("dir");
  528. var inputData = $input.data('inputmask');
  529. inputData['isRTL'] = true;
  530. $input.data('inputmask', inputData);
  531. isRTL = true;
  532. }
  533. //unbind all events - to make sure that no other mask will interfere when re-masking
  534. $input.unbind(".inputmask");
  535. $input.removeClass('focus.inputmask');
  536. //bind events
  537. $input.bind("mouseenter.inputmask", function () {
  538. var $input = $(this), input = this;
  539. if (!$input.hasClass('focus.inputmask')) {
  540. var nptL = input._valueGet().length;
  541. if (nptL == 0) {
  542. buffer = _buffer.slice();
  543. writeBuffer(input, buffer);
  544. } else if (nptL < buffer.length)
  545. writeBuffer(input, buffer);
  546. }
  547. }).bind("blur.inputmask", function () {
  548. var $input = $(this), input = this, nptValue = input._valueGet();
  549. $input.removeClass('focus.inputmask');
  550. if (nptValue != undoBuffer) {
  551. $input.change();
  552. }
  553. if (opts.clearMaskOnLostFocus) {
  554. if (nptValue == _buffer.join(''))
  555. input._valueSet('');
  556. else { //clearout optional tail of the mask
  557. clearOptionalTail(input, buffer);
  558. }
  559. }
  560. if ((opts.clearIncomplete || opts.onincomplete) && !isComplete(input)) {
  561. if (opts.onincomplete) {
  562. opts.onincomplete.call(input);
  563. }
  564. if (opts.clearIncomplete) {
  565. if (opts.clearMaskOnLostFocus)
  566. input._valueSet('');
  567. else {
  568. buffer = _buffer.slice();
  569. writeBuffer(input, buffer);
  570. }
  571. }
  572. }
  573. }).bind("focus.inputmask", function () {
  574. var $input = $(this), input = this;
  575. $input.addClass('focus.inputmask');
  576. undoBuffer = input._valueGet();
  577. }).bind("mouseleave.inputmask", function () {
  578. var $input = $(this), input = this;
  579. if (opts.clearMaskOnLostFocus) {
  580. if (!$input.hasClass('focus.inputmask')) {
  581. if (input._valueGet() == _buffer.join(''))
  582. input._valueSet('');
  583. else { //clearout optional tail of the mask
  584. clearOptionalTail(input, buffer);
  585. }
  586. }
  587. }
  588. }).bind("click.inputmask", function () {
  589. var input = this;
  590. setTimeout(function () {
  591. var selectedCaret = caret(input);
  592. if (selectedCaret.begin == selectedCaret.end) {
  593. var clickPosition = selectedCaret.begin;
  594. lastPosition = checkVal(input, buffer, false);
  595. if (isRTL)
  596. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  597. else
  598. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  599. }
  600. }, 0);
  601. }).bind('dblclick.inputmask', function () {
  602. var input = this;
  603. setTimeout(function () {
  604. caret(input, 0, lastPosition);
  605. }, 0);
  606. }).bind("keydown.inputmask", keydownEvent
  607. ).bind("keypress.inputmask", keypressEvent
  608. ).bind("keyup.inputmask", keyupEvent
  609. ).bind(pasteEvent + ".inputmask, dragdrop.inputmask, drop.inputmask", function () {
  610. var input = this;
  611. setTimeout(function () {
  612. caret(input, checkVal(input, buffer, true));
  613. }, 0);
  614. }).bind('setvalue.inputmask', function () {
  615. var input = this;
  616. undoBuffer = input._valueGet();
  617. checkVal(input, buffer, true);
  618. if (input._valueGet() == _buffer.join(''))
  619. input._valueSet('');
  620. });
  621. //apply mask
  622. lastPosition = checkVal(el, buffer, true);
  623. if (document.activeElement === el) { //position the caret when in focus
  624. $input.addClass('focus.inputmask');
  625. caret(el, lastPosition);
  626. } else if (opts.clearMaskOnLostFocus && el._valueGet() == _buffer.join(''))
  627. el._valueSet('');
  628. installEventRuler(el);
  629. //private functions
  630. function isComplete(npt) {
  631. var complete = true, nptValue = npt._valueGet(), ml = nptValue.length;
  632. for (var i = 0; i < ml; i++) {
  633. if (isMask(i) && nptValue.charAt(i) == getPlaceHolder(i)) {
  634. complete = false;
  635. break;
  636. }
  637. }
  638. return complete;
  639. }
  640. function installEventRuler(npt) {
  641. var events = $._data(npt).events;
  642. $.each(events, function (eventType, eventHandlers) {
  643. $(npt).bind(eventType + ".inputmask", function (event) {
  644. if (this.readOnly || this.disabled) {
  645. event.stopPropagation();
  646. event.stopImmediatePropagation();
  647. event.preventDefault();
  648. return false;
  649. }
  650. });
  651. //!! the bound handlers are executed in the order they where bound
  652. //reorder the events
  653. var ourHandler = eventHandlers[eventHandlers.length - 1];
  654. for (var i = eventHandlers.length - 1; i > 0; i--) {
  655. eventHandlers[i] = eventHandlers[i - 1];
  656. }
  657. eventHandlers[0] = ourHandler;
  658. });
  659. }
  660. function patchValueProperty(npt) {
  661. var valueProperty;
  662. if (Object.getOwnPropertyDescriptor)
  663. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  664. if (valueProperty && valueProperty.get) {
  665. if (!npt._valueGet) {
  666. npt._valueGet = valueProperty.get;
  667. npt._valueSet = valueProperty.set;
  668. Object.defineProperty(npt, "value", {
  669. get: function () {
  670. var $self = $(this), inputData = $(this).data('inputmask');
  671. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  672. },
  673. set: function (value) {
  674. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  675. }
  676. });
  677. }
  678. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  679. if (!npt._valueGet) {
  680. npt._valueGet = npt.__lookupGetter__("value");
  681. npt._valueSet = npt.__lookupSetter__("value");
  682. npt.__defineGetter__("value", function () {
  683. var $self = $(this), inputData = $(this).data('inputmask');
  684. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  685. });
  686. npt.__defineSetter__("value", function (value) {
  687. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  688. });
  689. }
  690. } else {
  691. if (!npt._valueGet) {
  692. npt._valueGet = function () { return this.value; }
  693. npt._valueSet = function (value) { this.value = value; }
  694. }
  695. if ($.fn.val.inputmaskpatch != true) {
  696. $.fn.val = function () {
  697. if (arguments.length == 0) {
  698. var $self = $(this);
  699. if ($self.data('inputmask')) {
  700. if ($self.data('inputmask')['autoUnmask'])
  701. return $self.inputmask('unmaskedvalue');
  702. else {
  703. var result = $.inputmask.val.apply($self);
  704. return result != $self.data('inputmask')['_buffer'].join('') ? result : '';
  705. }
  706. } else return $.inputmask.val.apply($self);
  707. } else {
  708. var args = arguments;
  709. return this.each(function () {
  710. var $self = $(this);
  711. var result = $.inputmask.val.apply($self, args);
  712. if ($self.data('inputmask')) $self.triggerHandler('setvalue.inputmask');
  713. return result;
  714. });
  715. }
  716. };
  717. $.extend($.fn.val, {
  718. inputmaskpatch: true
  719. });
  720. }
  721. }
  722. }
  723. //shift chars to left from start to end and put c at end position if defined
  724. function shiftL(start, end, c) {
  725. while (!isMask(start) && start - 1 >= 0) start--;
  726. for (var i = start; i < end && i < getMaskLength(); i++) {
  727. if (isMask(i)) {
  728. setReTargetPlaceHolder(buffer, i);
  729. var j = seekNext(buffer, i);
  730. var p = getBufferElement(buffer, j);
  731. if (p != getPlaceHolder(j)) {
  732. if (j < getMaskLength() && isValid(i, p, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def) {
  733. setBufferElement(buffer, i, getBufferElement(buffer, j));
  734. setReTargetPlaceHolder(buffer, j); //cleanup next position
  735. } else {
  736. if (isMask(i))
  737. break;
  738. }
  739. } else if (c == undefined) break;
  740. } else {
  741. setReTargetPlaceHolder(buffer, i);
  742. }
  743. }
  744. if (c != undefined)
  745. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  746. buffer = truncateInput(buffer.join(''), isRTL).split('');
  747. if (buffer.length == 0) buffer = _buffer.slice();
  748. return start; //return the used start position
  749. }
  750. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  751. for (var i = start; i <= end && i < getMaskLength(); i++) {
  752. if (isMask(i)) {
  753. var t = getBufferElement(buffer, i);
  754. setBufferElement(buffer, i, c);
  755. if (t != getPlaceHolder(i)) {
  756. var j = seekNext(buffer, i);
  757. if (j < getMaskLength()) {
  758. if (isValid(j, t, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def)
  759. c = t;
  760. else {
  761. if (isMask(j))
  762. break;
  763. else c = t;
  764. }
  765. } else break;
  766. } else if (full !== true) break;
  767. } else
  768. setReTargetPlaceHolder(buffer, i);
  769. }
  770. var lengthBefore = buffer.length;
  771. buffer = truncateInput(buffer.join(''), isRTL).split('');
  772. if (buffer.length == 0) buffer = _buffer.slice();
  773. return end - (lengthBefore - buffer.length); //return new start position
  774. };
  775. function keydownEvent(e) {
  776. //Safari 5.1.x - modal dialog fires keypress twice workaround
  777. skipKeyPressEvent = false;
  778. var input = this, k = e.keyCode, pos = caret(input);
  779. //set input direction according the position to the radixPoint
  780. if (opts.numericInput) {
  781. var nptStr = input._valueGet();
  782. var radixPosition = nptStr.indexOf(opts.radixPoint);
  783. if (radixPosition != -1) {
  784. isRTL = pos.begin <= radixPosition || pos.end <= radixPosition;
  785. }
  786. }
  787. //backspace, delete, and escape get special treatment
  788. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  789. var maskL = getMaskLength();
  790. if (pos.begin == 0 && pos.end == maskL) {
  791. buffer = _buffer.slice();
  792. writeBuffer(input, buffer);
  793. caret(input, checkVal(input, buffer, false));
  794. } else if ((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) {
  795. clearBuffer(buffer, pos.begin, pos.end);
  796. writeBuffer(input, buffer, isRTL ? checkVal(input, buffer, false) : pos.begin);
  797. } else {
  798. var beginPos = pos.begin - (k == opts.keyCode.DELETE ? 0 : 1);
  799. if (beginPos < firstMaskPos && k == opts.keyCode.DELETE) {
  800. beginPos = firstMaskPos;
  801. }
  802. if (beginPos >= firstMaskPos) {
  803. if (opts.numericInput && opts.greedy && k == opts.keyCode.DELETE && buffer[beginPos] == opts.radixPoint) {
  804. beginPos = seekNext(buffer, beginPos);
  805. isRTL = false;
  806. }
  807. if (isRTL) {
  808. beginPos = shiftR(firstMaskPos, beginPos, getPlaceHolder(beginPos), true);
  809. beginPos = (opts.numericInput && opts.greedy && k == opts.keyCode.BACKSPACE && buffer[beginPos + 1] == opts.radixPoint) ? beginPos + 1 : seekNext(buffer, beginPos);
  810. } else beginPos = shiftL(beginPos, maskL);
  811. writeBuffer(input, buffer, beginPos);
  812. }
  813. }
  814. if (opts.oncleared && input._valueGet() == _buffer.join(''))
  815. opts.oncleared.call(input);
  816. return false;
  817. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  818. setTimeout(function () {
  819. var caretPos = checkVal(input, buffer, false, true);
  820. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  821. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  822. }, 0);
  823. return false;
  824. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  825. caret(input, 0, e.shiftKey ? pos.begin : 0);
  826. return false;
  827. }
  828. else if (k == opts.keyCode.ESCAPE) {//escape
  829. input._valueSet(undoBuffer);
  830. caret(input, 0, checkVal(input, buffer));
  831. return false;
  832. } else if (k == opts.keyCode.INSERT) {//insert
  833. opts.insertMode = !opts.insertMode;
  834. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  835. return false;
  836. } else if (e.ctrlKey && k == 88) {
  837. setTimeout(function () {
  838. caret(input, checkVal(input, buffer, true));
  839. }, 0);
  840. } else if (!opts.insertMode) { //overwritemode
  841. if (k == opts.keyCode.RIGHT) {//right
  842. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  843. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  844. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  845. return false;
  846. } else if (k == opts.keyCode.LEFT) {//left
  847. var caretPos = pos.begin - 1;
  848. caretPos = caretPos > 0 ? caretPos : 0;
  849. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  850. return false;
  851. }
  852. }
  853. opts.onKeyDown.call(this, e, opts); //extra stuff to execute on keydown
  854. ignorable = $.inArray(k, opts.ignorables) != -1;
  855. }
  856. function keypressEvent(e) {
  857. //Safari 5.1.x - modal dialog fires keypress twice workaround
  858. if (skipKeyPressEvent) return false;
  859. skipKeyPressEvent = true;
  860. var input = this;
  861. e = e || window.event;
  862. var k = e.which || e.charCode || e.keyCode;
  863. if (opts.numericInput && k == opts.radixPoint.charCodeAt(opts.radixPoint.length - 1)) {
  864. var nptStr = input._valueGet();
  865. var radixPosition = nptStr.indexOf(opts.radixPoint);
  866. caret(input, seekNext(buffer, radixPosition != -1 ? radixPosition : getMaskLength()));
  867. }
  868. if (e.ctrlKey || e.altKey || e.metaKey || ignorable) {//Ignore
  869. return true;
  870. } else {
  871. if (k) {
  872. var pos = caret(input), c = String.fromCharCode(k), maskL = getMaskLength();
  873. clearBuffer(buffer, pos.begin, pos.end);
  874. if (isRTL) {
  875. var p = opts.numericInput ? pos.end : seekPrevious(buffer, pos.end), np;
  876. if ((np = isValid(p == maskL || getBufferElement(buffer, p) == opts.radixPoint ? seekPrevious(buffer, p) : p, c, buffer, false)) !== false) {
  877. if (np !== true) {
  878. p = np.pos || pos; //set new position from isValid
  879. c = np.c || c; //set new char from isValid
  880. }
  881. var firstUnmaskedPosition = firstMaskPos;
  882. if (opts.insertMode == true) {
  883. if (opts.greedy == true) {
  884. var bfrClone = buffer.slice();
  885. while (getBufferElement(bfrClone, firstUnmaskedPosition, true) != getPlaceHolder(firstUnmaskedPosition) && firstUnmaskedPosition <= p) {
  886. firstUnmaskedPosition = seekNext(buffer, firstUnmaskedPosition);
  887. }
  888. }
  889. if (firstUnmaskedPosition <= p && (opts.greedy || buffer.length < maskL)) {
  890. if (buffer[firstMaskPos] != getPlaceHolder(firstMaskPos) && buffer.length < maskL) {
  891. var offset = prepareBuffer(buffer, -1, isRTL);
  892. if (pos.end != 0) p = p + offset;
  893. maskL = buffer.length;
  894. }
  895. shiftL(firstUnmaskedPosition, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  896. } else return false;
  897. } else setBufferElement(buffer, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  898. writeBuffer(input, buffer, opts.numericInput && p == 0 ? seekNext(buffer, p) : p);
  899. if (opts.oncomplete && isComplete(input))
  900. opts.oncomplete.call(input);
  901. } else if (android) writeBuffer(input, buffer, pos.begin);
  902. }
  903. else {
  904. var p = seekNext(buffer, pos.begin - 1), np;
  905. prepareBuffer(buffer, p, isRTL);
  906. if ((np = isValid(p, c, buffer, false)) !== false) {
  907. if (np !== true) {
  908. p = np.pos || p; //set new position from isValid
  909. c = np.c || c; //set new char from isValid
  910. }
  911. if (opts.insertMode == true) {
  912. var lastUnmaskedPosition = getMaskLength();
  913. var bfrClone = buffer.slice();
  914. while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
  915. lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(buffer, lastUnmaskedPosition);
  916. }
  917. if (lastUnmaskedPosition >= p)
  918. shiftR(p, buffer.length, c);
  919. else return false;
  920. }
  921. else setBufferElement(buffer, p, c);
  922. var next = seekNext(buffer, p);
  923. writeBuffer(input, buffer, next);
  924. if (opts.oncomplete && isComplete(input))
  925. opts.oncomplete.call(input);
  926. } else if (android) writeBuffer(input, buffer, pos.begin);
  927. }
  928. return false;
  929. }
  930. }
  931. }
  932. function keyupEvent(e) {
  933. var $input = $(this), input = this;
  934. var k = e.keyCode;
  935. opts.onKeyUp.call(this, e, opts); //extra stuff to execute on keyup
  936. if (k == opts.keyCode.TAB && $input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  937. buffer = _buffer.slice();
  938. writeBuffer(input, buffer);
  939. if (!isRTL) caret(input, 0);
  940. undoBuffer = input._valueGet();
  941. }
  942. }
  943. }
  944. };
  945. }
  946. })(jQuery);