jquery.inputmask.js 49 KB

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