jquery.inputmask.js 55 KB

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