jquery.inputmask.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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.25
  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. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  622. var activeElement;
  623. try {
  624. activeElement = document.activeElement;
  625. } catch(e) {}
  626. if (activeElement === el) { //position the caret when in focus
  627. $input.addClass('focus.inputmask');
  628. caret(el, lastPosition);
  629. } else if (opts.clearMaskOnLostFocus) {
  630. if (el._valueGet() == _buffer.join('')) {
  631. el._valueSet('');
  632. } else {
  633. clearOptionalTail(el, buffer);
  634. }
  635. }
  636. installEventRuler(el);
  637. //private functions
  638. function isComplete(npt) {
  639. var complete = true, nptValue = npt._valueGet(), ml = nptValue.length;
  640. for (var i = 0; i < ml; i++) {
  641. if (isMask(i) && nptValue.charAt(i) == getPlaceHolder(i)) {
  642. complete = false;
  643. break;
  644. }
  645. }
  646. return complete;
  647. }
  648. function installEventRuler(npt) {
  649. var events = $._data(npt).events;
  650. $.each(events, function (eventType, eventHandlers) {
  651. $(npt).bind(eventType + ".inputmask", function (event) {
  652. if (this.readOnly || this.disabled) {
  653. event.stopPropagation();
  654. event.stopImmediatePropagation();
  655. event.preventDefault();
  656. return false;
  657. }
  658. });
  659. //!! the bound handlers are executed in the order they where bound
  660. //reorder the events
  661. var ourHandler = eventHandlers[eventHandlers.length - 1];
  662. for (var i = eventHandlers.length - 1; i > 0; i--) {
  663. eventHandlers[i] = eventHandlers[i - 1];
  664. }
  665. eventHandlers[0] = ourHandler;
  666. });
  667. }
  668. function patchValueProperty(npt) {
  669. var valueProperty;
  670. if (Object.getOwnPropertyDescriptor)
  671. valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  672. if (valueProperty && valueProperty.get) {
  673. if (!npt._valueGet) {
  674. npt._valueGet = valueProperty.get;
  675. npt._valueSet = valueProperty.set;
  676. Object.defineProperty(npt, "value", {
  677. get: function () {
  678. var $self = $(this), inputData = $(this).data('inputmask');
  679. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  680. },
  681. set: function (value) {
  682. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  683. }
  684. });
  685. }
  686. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  687. if (!npt._valueGet) {
  688. npt._valueGet = npt.__lookupGetter__("value");
  689. npt._valueSet = npt.__lookupSetter__("value");
  690. npt.__defineGetter__("value", function () {
  691. var $self = $(this), inputData = $(this).data('inputmask');
  692. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  693. });
  694. npt.__defineSetter__("value", function (value) {
  695. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  696. });
  697. }
  698. } else {
  699. if (!npt._valueGet) {
  700. npt._valueGet = function () { return this.value; }
  701. npt._valueSet = function (value) { this.value = value; }
  702. }
  703. if ($.fn.val.inputmaskpatch != true) {
  704. $.fn.val = function () {
  705. if (arguments.length == 0) {
  706. var $self = $(this);
  707. if ($self.data('inputmask')) {
  708. if ($self.data('inputmask')['autoUnmask'])
  709. return $self.inputmask('unmaskedvalue');
  710. else {
  711. var result = $.inputmask.val.apply($self);
  712. return result != $self.data('inputmask')['_buffer'].join('') ? result : '';
  713. }
  714. } else return $.inputmask.val.apply($self);
  715. } else {
  716. var args = arguments;
  717. return this.each(function () {
  718. var $self = $(this);
  719. var result = $.inputmask.val.apply($self, args);
  720. if ($self.data('inputmask')) $self.triggerHandler('setvalue.inputmask');
  721. return result;
  722. });
  723. }
  724. };
  725. $.extend($.fn.val, {
  726. inputmaskpatch: true
  727. });
  728. }
  729. }
  730. }
  731. //shift chars to left from start to end and put c at end position if defined
  732. function shiftL(start, end, c) {
  733. while (!isMask(start) && start - 1 >= 0) start--;
  734. for (var i = start; i < end && i < getMaskLength(); i++) {
  735. if (isMask(i)) {
  736. setReTargetPlaceHolder(buffer, i);
  737. var j = seekNext(buffer, i);
  738. var p = getBufferElement(buffer, j);
  739. if (p != getPlaceHolder(j)) {
  740. if (j < getMaskLength() && isValid(i, p, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def) {
  741. setBufferElement(buffer, i, getBufferElement(buffer, j));
  742. setReTargetPlaceHolder(buffer, j); //cleanup next position
  743. } else {
  744. if (isMask(i))
  745. break;
  746. }
  747. } else if (c == undefined) break;
  748. } else {
  749. setReTargetPlaceHolder(buffer, i);
  750. }
  751. }
  752. if (c != undefined)
  753. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  754. buffer = truncateInput(buffer.join(''), isRTL).split('');
  755. if (buffer.length == 0) buffer = _buffer.slice();
  756. return start; //return the used start position
  757. }
  758. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  759. for (var i = start; i <= end && i < getMaskLength(); i++) {
  760. if (isMask(i)) {
  761. var t = getBufferElement(buffer, i);
  762. setBufferElement(buffer, i, c);
  763. if (t != getPlaceHolder(i)) {
  764. var j = seekNext(buffer, i);
  765. if (j < getMaskLength()) {
  766. if (isValid(j, t, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def)
  767. c = t;
  768. else {
  769. if (isMask(j))
  770. break;
  771. else c = t;
  772. }
  773. } else break;
  774. } else if (full !== true) break;
  775. } else
  776. setReTargetPlaceHolder(buffer, i);
  777. }
  778. var lengthBefore = buffer.length;
  779. buffer = truncateInput(buffer.join(''), isRTL).split('');
  780. if (buffer.length == 0) buffer = _buffer.slice();
  781. return end - (lengthBefore - buffer.length); //return new start position
  782. };
  783. function keydownEvent(e) {
  784. //Safari 5.1.x - modal dialog fires keypress twice workaround
  785. skipKeyPressEvent = false;
  786. var input = this, k = e.keyCode, pos = caret(input);
  787. //set input direction according the position to the radixPoint
  788. if (opts.numericInput) {
  789. var nptStr = input._valueGet();
  790. var radixPosition = nptStr.indexOf(opts.radixPoint);
  791. if (radixPosition != -1) {
  792. isRTL = pos.begin <= radixPosition || pos.end <= radixPosition;
  793. }
  794. }
  795. //backspace, delete, and escape get special treatment
  796. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  797. var maskL = getMaskLength();
  798. if (pos.begin == 0 && pos.end == maskL) {
  799. buffer = _buffer.slice();
  800. writeBuffer(input, buffer);
  801. caret(input, checkVal(input, buffer, false));
  802. } else if ((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) {
  803. clearBuffer(buffer, pos.begin, pos.end);
  804. writeBuffer(input, buffer, isRTL ? checkVal(input, buffer, false) : pos.begin);
  805. } else {
  806. var beginPos = pos.begin - (k == opts.keyCode.DELETE ? 0 : 1);
  807. if (beginPos < firstMaskPos && k == opts.keyCode.DELETE) {
  808. beginPos = firstMaskPos;
  809. }
  810. if (beginPos >= firstMaskPos) {
  811. if (opts.numericInput && opts.greedy && k == opts.keyCode.DELETE && buffer[beginPos] == opts.radixPoint) {
  812. beginPos = seekNext(buffer, beginPos);
  813. isRTL = false;
  814. }
  815. if (isRTL) {
  816. beginPos = shiftR(firstMaskPos, beginPos, getPlaceHolder(beginPos), true);
  817. beginPos = (opts.numericInput && opts.greedy && k == opts.keyCode.BACKSPACE && buffer[beginPos + 1] == opts.radixPoint) ? beginPos + 1 : seekNext(buffer, beginPos);
  818. } else beginPos = shiftL(beginPos, maskL);
  819. writeBuffer(input, buffer, beginPos);
  820. }
  821. }
  822. if (opts.oncleared && input._valueGet() == _buffer.join(''))
  823. opts.oncleared.call(input);
  824. return false;
  825. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  826. setTimeout(function () {
  827. var caretPos = checkVal(input, buffer, false, true);
  828. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  829. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  830. }, 0);
  831. return false;
  832. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  833. caret(input, 0, e.shiftKey ? pos.begin : 0);
  834. return false;
  835. }
  836. else if (k == opts.keyCode.ESCAPE) {//escape
  837. input._valueSet(undoBuffer);
  838. caret(input, 0, checkVal(input, buffer));
  839. return false;
  840. } else if (k == opts.keyCode.INSERT) {//insert
  841. opts.insertMode = !opts.insertMode;
  842. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  843. return false;
  844. } else if (e.ctrlKey && k == 88) {
  845. setTimeout(function () {
  846. caret(input, checkVal(input, buffer, true));
  847. }, 0);
  848. } else if (!opts.insertMode) { //overwritemode
  849. if (k == opts.keyCode.RIGHT) {//right
  850. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  851. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  852. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  853. return false;
  854. } else if (k == opts.keyCode.LEFT) {//left
  855. var caretPos = pos.begin - 1;
  856. caretPos = caretPos > 0 ? caretPos : 0;
  857. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  858. return false;
  859. }
  860. }
  861. opts.onKeyDown.call(this, e, opts); //extra stuff to execute on keydown
  862. ignorable = $.inArray(k, opts.ignorables) != -1;
  863. }
  864. function keypressEvent(e) {
  865. //Safari 5.1.x - modal dialog fires keypress twice workaround
  866. if (skipKeyPressEvent) return false;
  867. skipKeyPressEvent = true;
  868. var input = this;
  869. e = e || window.event;
  870. var k = e.which || e.charCode || e.keyCode;
  871. if (opts.numericInput && k == opts.radixPoint.charCodeAt(opts.radixPoint.length - 1)) {
  872. var nptStr = input._valueGet();
  873. var radixPosition = nptStr.indexOf(opts.radixPoint);
  874. caret(input, seekNext(buffer, radixPosition != -1 ? radixPosition : getMaskLength()));
  875. }
  876. if (e.ctrlKey || e.altKey || e.metaKey || ignorable) {//Ignore
  877. return true;
  878. } else {
  879. if (k) {
  880. var pos = caret(input), c = String.fromCharCode(k), maskL = getMaskLength();
  881. clearBuffer(buffer, pos.begin, pos.end);
  882. if (isRTL) {
  883. var p = opts.numericInput ? pos.end : seekPrevious(buffer, pos.end), np;
  884. if ((np = isValid(p == maskL || getBufferElement(buffer, p) == opts.radixPoint ? seekPrevious(buffer, p) : p, c, buffer, false)) !== false) {
  885. if (np !== true) {
  886. p = np.pos || pos; //set new position from isValid
  887. c = np.c || c; //set new char from isValid
  888. }
  889. var firstUnmaskedPosition = firstMaskPos;
  890. if (opts.insertMode == true) {
  891. if (opts.greedy == true) {
  892. var bfrClone = buffer.slice();
  893. while (getBufferElement(bfrClone, firstUnmaskedPosition, true) != getPlaceHolder(firstUnmaskedPosition) && firstUnmaskedPosition <= p) {
  894. firstUnmaskedPosition = firstUnmaskedPosition == maskL ? (maskL + 1) : seekNext(buffer, firstUnmaskedPosition);
  895. }
  896. }
  897. if (firstUnmaskedPosition <= p && (opts.greedy || buffer.length < maskL)) {
  898. if (buffer[firstMaskPos] != getPlaceHolder(firstMaskPos) && buffer.length < maskL) {
  899. var offset = prepareBuffer(buffer, -1, isRTL);
  900. if (pos.end != 0) p = p + offset;
  901. maskL = buffer.length;
  902. }
  903. shiftL(firstUnmaskedPosition, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  904. } else return false;
  905. } else setBufferElement(buffer, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  906. writeBuffer(input, buffer, opts.numericInput && p == 0 ? seekNext(buffer, p) : p);
  907. if (opts.oncomplete && isComplete(input))
  908. opts.oncomplete.call(input);
  909. } else if (android) writeBuffer(input, buffer, pos.begin);
  910. }
  911. else {
  912. var p = seekNext(buffer, pos.begin - 1), np;
  913. prepareBuffer(buffer, p, isRTL);
  914. if ((np = isValid(p, c, buffer, false)) !== false) {
  915. if (np !== true) {
  916. p = np.pos || p; //set new position from isValid
  917. c = np.c || c; //set new char from isValid
  918. }
  919. if (opts.insertMode == true) {
  920. var lastUnmaskedPosition = getMaskLength();
  921. var bfrClone = buffer.slice();
  922. while (getBufferElement(bfrClone, lastUnmaskedPosition, true) != getPlaceHolder(lastUnmaskedPosition) && lastUnmaskedPosition >= p) {
  923. lastUnmaskedPosition = lastUnmaskedPosition == 0 ? -1 : seekPrevious(buffer, lastUnmaskedPosition);
  924. }
  925. if (lastUnmaskedPosition >= p)
  926. shiftR(p, buffer.length, c);
  927. else return false;
  928. }
  929. else setBufferElement(buffer, p, c);
  930. var next = seekNext(buffer, p);
  931. writeBuffer(input, buffer, next);
  932. if (opts.oncomplete && isComplete(input))
  933. opts.oncomplete.call(input);
  934. } else if (android) writeBuffer(input, buffer, pos.begin);
  935. }
  936. return false;
  937. }
  938. }
  939. }
  940. function keyupEvent(e) {
  941. var $input = $(this), input = this;
  942. var k = e.keyCode;
  943. opts.onKeyUp.call(this, e, opts); //extra stuff to execute on keyup
  944. if (k == opts.keyCode.TAB && $input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  945. buffer = _buffer.slice();
  946. writeBuffer(input, buffer);
  947. if (!isRTL) caret(input, 0);
  948. undoBuffer = input._valueGet();
  949. }
  950. }
  951. }
  952. };
  953. }
  954. })(jQuery);