jquery.inputmask.js 53 KB

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