jquery.inputmask.js 56 KB

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