jquery.inputmask.js 54 KB

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