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