jquery.inputmask.js 57 KB

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