jquery.inputmask.js 57 KB

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