jquery.inputmask.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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.7
  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 tests[testPos].fn != null ? tests[testPos].fn.test(chrs, buffer, pos, strict, opts) : false;
  243. }
  244. function isMask(pos) {
  245. var testPos = determineTestPosition(pos);
  246. var test = tests[testPos];
  247. return test != undefined ? test.fn : false;
  248. }
  249. function determineTestPosition(pos) {
  250. return pos % tests.length;
  251. }
  252. function getPlaceHolder(pos) {
  253. return opts.placeholder.charAt(pos % opts.placeholder.length);
  254. }
  255. function getMaskLength() {
  256. var calculatedLength = _buffer.length;
  257. if (!opts.greedy && opts.repeat > 1) {
  258. calculatedLength += (_buffer.length * (opts.repeat - 1))
  259. }
  260. return calculatedLength;
  261. }
  262. //pos: from position
  263. function seekNext(buffer, pos) {
  264. var maskL = getMaskLength();
  265. if (pos >= maskL) return maskL;
  266. var position = pos;
  267. while (++position < maskL && !isMask(position)) { };
  268. return position;
  269. }
  270. //pos: from position
  271. function seekPrevious(buffer, pos) {
  272. var position = pos;
  273. if (position <= 0) return 0;
  274. while (--position > 0 && !isMask(position)) { };
  275. return position;
  276. }
  277. function setBufferElement(buffer, position, element) {
  278. //position = prepareBuffer(buffer, position);
  279. var test = tests[determineTestPosition(position)];
  280. var elem = element;
  281. switch (test.casing) {
  282. case "upper":
  283. elem = element.toUpperCase();
  284. break;
  285. case "lower":
  286. elem = element.toLowerCase();
  287. break;
  288. }
  289. buffer[position] = elem;
  290. }
  291. function getBufferElement(buffer, position) {
  292. //position = prepareBuffer(buffer, position);
  293. return buffer[position];
  294. }
  295. //needed to handle the non-greedy mask repetitions
  296. function prepareBuffer(buffer, position, isRTL) {
  297. var j = 0;
  298. if (isRTL) {
  299. while (position < 0 && buffer.length < getMaskLength()) {
  300. j = _buffer.length - 1;
  301. position = _buffer.length;
  302. while (_buffer[j] !== undefined) {
  303. buffer.unshift(_buffer[j--]);
  304. }
  305. }
  306. } else {
  307. while (buffer.length < position && buffer.length < getMaskLength()) {
  308. while (_buffer[j] !== undefined) {
  309. buffer.push(_buffer[j++]);
  310. }
  311. }
  312. }
  313. return position;
  314. }
  315. function writeBuffer(input, buffer, caretPos) {
  316. input._valueSet(buffer.join(''));
  317. if (caretPos != undefined) {
  318. if (android) {
  319. setTimeout(function() {
  320. caret(input, caretPos);
  321. }, 100);
  322. }
  323. else caret(input, caretPos);
  324. }
  325. };
  326. function clearBuffer(buffer, start, end) {
  327. for (var i = start, maskL = getMaskLength(); i < end && i < maskL; i++) {
  328. setBufferElement(buffer, i, getBufferElement(_buffer.slice(), i));
  329. }
  330. };
  331. function SetReTargetPlaceHolder(buffer, pos) {
  332. var testPos = determineTestPosition(pos);
  333. setBufferElement(buffer, pos, getBufferElement(_buffer, testPos));
  334. }
  335. function checkVal(input, buffer, clearInvalid, skipRadixHandling) {
  336. var isRTL = $(input).data('inputmask')['isRTL'],
  337. inputValue = TruncateInput(input._valueGet(), isRTL).split('');
  338. if (isRTL) { //align inputValue for RTL/numeric input
  339. var maskL = getMaskLength();
  340. var inputValueRev = inputValue.reverse(); inputValueRev.length = maskL;
  341. for (var i = 0; i < maskL; i++) {
  342. var targetPosition = determineTestPosition(maskL - (i + 1));
  343. if (tests[targetPosition].fn == null && inputValueRev[i] != getBufferElement(_buffer, targetPosition)) {
  344. inputValueRev.splice(i, 0, getBufferElement(_buffer, targetPosition));
  345. inputValueRev.length = maskL;
  346. } else {
  347. inputValueRev[i] = inputValueRev[i] || getBufferElement(_buffer, targetPosition);
  348. }
  349. }
  350. inputValue = inputValueRev.reverse();
  351. }
  352. clearBuffer(buffer, 0, buffer.length);
  353. buffer.length = _buffer.length;
  354. var lastMatch = -1, checkPosition = -1, np, maskL = getMaskLength(), ivl = inputValue.length, rtlMatch = ivl == 0 ? maskL : -1;
  355. for (var i = 0; i < ivl; i++) {
  356. for (var pos = checkPosition + 1; pos < maskL; pos++) {
  357. if (isMask(pos)) {
  358. var c = inputValue[i];
  359. if ((np = isValid(pos, c, buffer, !clearInvalid)) !== false) {
  360. if (np !== true) pos = np; //set new position from isValid
  361. setBufferElement(buffer, pos, c);
  362. lastMatch = checkPosition = pos;
  363. } else {
  364. SetReTargetPlaceHolder(buffer, pos);
  365. if (c == getPlaceHolder(pos)) {
  366. checkPosition = pos;
  367. rtlMatch = pos;
  368. }
  369. }
  370. break;
  371. } else { //nonmask
  372. SetReTargetPlaceHolder(buffer, pos);
  373. if (lastMatch == checkPosition) //once outsync the nonmask cannot be the lastmatch
  374. lastMatch = pos;
  375. checkPosition = pos;
  376. if (inputValue[i] == getBufferElement(buffer, pos))
  377. break;
  378. }
  379. }
  380. }
  381. //Truncate buffer when using non-greedy masks
  382. if (opts.greedy == false) {
  383. var newBuffer = TruncateInput(buffer.join(''), isRTL).split('');
  384. while (buffer.length != newBuffer.length) { //map changes into the original buffer
  385. isRTL ? buffer.shift() : buffer.pop();
  386. }
  387. }
  388. if (clearInvalid) {
  389. writeBuffer(input, buffer);
  390. }
  391. 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);
  392. }
  393. function EscapeRegex(str) {
  394. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
  395. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  396. }
  397. function TruncateInput(inputValue, rtl) {
  398. return rtl ? inputValue.replace(new RegExp("^(" + EscapeRegex(_buffer.join('')) + ")*"), "") : inputValue.replace(new RegExp("(" + EscapeRegex(_buffer.join('')) + ")*$"), "");
  399. }
  400. function clearOptionalTail(input, buffer) {
  401. var tmpBuffer = buffer.slice();
  402. if ($(input).data('inputmask')['isRTL']) {
  403. for (var pos = 0; pos <= tmpBuffer.length - 1; pos++) {
  404. var testPos = determineTestPosition(pos);
  405. if (tests[testPos].optionality) {
  406. if (getPlaceHolder(pos) == buffer[pos] || !isMask(pos))
  407. tmpBuffer.splice(0, 1);
  408. else break;
  409. } else break;
  410. }
  411. } else {
  412. for (var pos = tmpBuffer.length - 1; pos >= 0; pos--) {
  413. var testPos = determineTestPosition(pos);
  414. if (tests[testPos].optionality) {
  415. if (getPlaceHolder(pos) == buffer[pos] || !isMask(pos))
  416. tmpBuffer.pop();
  417. else break;
  418. } else break;
  419. }
  420. }
  421. writeBuffer(input, tmpBuffer);
  422. }
  423. //functionality fn
  424. function unmaskedvalue($input, skipDatepickerCheck) {
  425. var input = $input[0];
  426. if (tests && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) {
  427. var buffer = _buffer.slice();
  428. checkVal(input, buffer);
  429. return $.map(buffer, function(element, index) {
  430. return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null;
  431. }).join('');
  432. }
  433. else {
  434. return input._valueGet();
  435. }
  436. }
  437. function caret(input, begin, end) {
  438. var npt = input.jquery && input.length > 0 ? input[0] : input;
  439. if (typeof begin == 'number') {
  440. end = (typeof end == 'number') ? end : begin;
  441. if (opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  442. if (npt.setSelectionRange) {
  443. npt.setSelectionRange(begin, end);
  444. } else if (npt.createTextRange) {
  445. var range = npt.createTextRange();
  446. range.collapse(true);
  447. range.moveEnd('character', end);
  448. range.moveStart('character', begin);
  449. range.select();
  450. }
  451. npt.focus();
  452. if (android && end != npt.selectionEnd) caretposCorrection = { begin: begin, end: end };
  453. } else {
  454. var caretpos = android ? caretposCorrection : null, caretposCorrection = null;
  455. if (caretpos == null) {
  456. if (npt.setSelectionRange) {
  457. begin = npt.selectionStart;
  458. end = npt.selectionEnd;
  459. } else if (document.selection && document.selection.createRange) {
  460. var range = document.selection.createRange();
  461. begin = 0 - range.duplicate().moveStart('character', -100000);
  462. end = begin + range.text.length;
  463. }
  464. caretpos = { begin: begin, end: end };
  465. }
  466. return caretpos;
  467. }
  468. };
  469. function mask(el) {
  470. var $input = $(el);
  471. if (!$input.is(":input")) return;
  472. //store tests & original buffer in the input element - used to get the unmasked value
  473. $input.data('inputmask', {
  474. 'tests': tests,
  475. '_buffer': _buffer,
  476. 'greedy': opts.greedy,
  477. 'repeat': opts.repeat,
  478. 'autoUnmask': opts.autoUnmask,
  479. 'definitions': opts.definitions,
  480. 'isRTL': false
  481. });
  482. patchValueProperty(el);
  483. //init vars
  484. var buffer = _buffer.slice(),
  485. undoBuffer = el._valueGet(),
  486. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  487. ignorable = false,
  488. lastPosition = -1,
  489. firstMaskPos = seekNext(buffer, -1),
  490. isRTL = false;
  491. if (el.dir == "rtl" || opts.numericInput) {
  492. el.dir = "ltr"
  493. $input.css("text-align", "right");
  494. $input.removeAttr("dir");
  495. inputData = $input.data('inputmask');
  496. inputData['isRTL'] = true;
  497. $input.data('inputmask', inputData);
  498. isRTL = true;
  499. }
  500. //unbind all events - to make sure that no other mask will interfere when re-masking
  501. $input.unbind(".inputmask");
  502. $input.removeClass('focus.inputmask');
  503. //bind events
  504. $input.bind("mouseenter.inputmask", function() {
  505. var $input = $(this), input = this;
  506. if (!$input.hasClass('focus.inputmask')) {
  507. var nptL = input._valueGet().length;
  508. if (nptL == 0) {
  509. buffer = _buffer.slice();
  510. writeBuffer(input, buffer);
  511. } else if (nptL < buffer.length)
  512. writeBuffer(input, buffer);
  513. }
  514. }).bind("blur.inputmask", function() {
  515. var $input = $(this), input = this, nptValue = input._valueGet();
  516. $input.removeClass('focus.inputmask');
  517. if (nptValue != undoBuffer) {
  518. $input.change();
  519. }
  520. if (opts.clearMaskOnLostFocus) {
  521. if (nptValue == _buffer.join(''))
  522. input._valueSet('');
  523. else { //clearout optional tail of the mask
  524. clearOptionalTail(input, buffer);
  525. }
  526. }
  527. if ((opts.clearIncomplete || opts.onincomplete) && checkVal(input, buffer, true) != getMaskLength()) {
  528. if (opts.onincomplete) {
  529. opts.onincomplete.call(input);
  530. }
  531. if (opts.clearIncomplete) {
  532. if (opts.clearMaskOnLostFocus)
  533. input._valueSet('');
  534. else {
  535. buffer = _buffer.slice();
  536. writeBuffer(input, buffer);
  537. }
  538. }
  539. }
  540. }).bind("focus.inputmask", function() {
  541. var $input = $(this), input = this;
  542. $input.addClass('focus.inputmask');
  543. undoBuffer = input._valueGet();
  544. }).bind("mouseleave.inputmask", function() {
  545. var $input = $(this), input = this;
  546. if (opts.clearMaskOnLostFocus) {
  547. if (!$input.hasClass('focus.inputmask')) {
  548. if (input._valueGet() == _buffer.join(''))
  549. input._valueSet('');
  550. else { //clearout optional tail of the mask
  551. clearOptionalTail(input, buffer);
  552. }
  553. }
  554. }
  555. }).bind("click.inputmask", function() {
  556. var input = this;
  557. setTimeout(function() {
  558. var selectedCaret = caret(input);
  559. if (selectedCaret.begin == selectedCaret.end) {
  560. var clickPosition = selectedCaret.begin;
  561. lastPosition = checkVal(input, buffer, false);
  562. if (isRTL)
  563. caret(input, clickPosition > lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  564. else
  565. caret(input, clickPosition < lastPosition && (isValid(clickPosition, buffer[clickPosition], buffer, true) !== false || !isMask(clickPosition)) ? clickPosition : lastPosition);
  566. }
  567. }, 0);
  568. }).bind('dblclick.inputmask', function() {
  569. var input = this;
  570. setTimeout(function() {
  571. caret(input, 0, lastPosition);
  572. }, 0);
  573. }).bind("keydown.inputmask", keydownEvent
  574. ).bind("keypress.inputmask", keypressEvent
  575. ).bind("keyup.inputmask", keyupEvent
  576. ).bind(pasteEventName, function() {
  577. var input = this;
  578. setTimeout(function() {
  579. caret(input, checkVal(input, buffer, true));
  580. }, 0);
  581. }).bind('setvalue.inputmask', function() {
  582. var input = this;
  583. undoBuffer = input._valueGet();
  584. checkVal(input, buffer, true);
  585. if (input._valueGet() == _buffer.join(''))
  586. input._valueSet('');
  587. });
  588. //apply mask
  589. lastPosition = checkVal(el, buffer, true);
  590. if (document.activeElement === el) { //position the caret when in focus
  591. $input.addClass('focus.inputmask');
  592. caret(el, lastPosition);
  593. } else if (opts.clearMaskOnLostFocus && el._valueGet() == _buffer.join(''))
  594. el._valueSet('');
  595. //private functions
  596. function patchValueProperty(npt) {
  597. var valueProperty;
  598. if (Object.getOwnPropertyDescriptor)
  599. var valueProperty = Object.getOwnPropertyDescriptor(npt, "value");
  600. if (valueProperty && valueProperty.get) {
  601. if (!npt._valueGet) {
  602. npt._valueGet = valueProperty.get;
  603. npt._valueSet = valueProperty.set;
  604. Object.defineProperty(npt, "value", {
  605. get: function() {
  606. var $self = $(this), inputData = $(this).data('inputmask');
  607. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  608. },
  609. set: function(value) {
  610. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  611. }
  612. });
  613. }
  614. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  615. if (!npt._valueGet) {
  616. npt._valueGet = npt.__lookupGetter__("value");
  617. npt._valueSet = npt.__lookupSetter__("value");
  618. npt.__defineGetter__("value", function() {
  619. var $self = $(this), inputData = $(this).data('inputmask');
  620. return inputData && inputData['autoUnmask'] ? $self.inputmask('unmaskedvalue') : this._valueGet() != inputData['_buffer'].join('') ? this._valueGet() : '';
  621. });
  622. npt.__defineSetter__("value", function(value) {
  623. this._valueSet(value); $(this).triggerHandler('setvalue.inputmask');
  624. });
  625. }
  626. } else {
  627. if (!npt._valueGet) {
  628. npt._valueGet = function() { return this.value; }
  629. npt._valueSet = function(value) { this.value = value; }
  630. }
  631. if ($.fn.val.inputmaskpatch != true) {
  632. $.fn.val = function() {
  633. if (arguments.length == 0) {
  634. var $self = $(this);
  635. if ($self.data('inputmask')) {
  636. if ($self.data('inputmask')['autoUnmask'])
  637. return $self.inputmask('unmaskedvalue');
  638. else {
  639. var result = $.inputmask.val.apply($self);
  640. return result != $self.data('inputmask')['_buffer'].join('') ? result : '';
  641. }
  642. } else return $.inputmask.val.apply($self);
  643. } else {
  644. var args = arguments;
  645. return this.each(function() {
  646. var $self = $(this);
  647. var result = $.inputmask.val.apply($self, args);
  648. if ($self.data('inputmask')) $self.triggerHandler('setvalue.inputmask');
  649. return result;
  650. });
  651. }
  652. };
  653. $.extend($.fn.val, {
  654. inputmaskpatch: true
  655. });
  656. }
  657. }
  658. }
  659. //shift chars to left from start to end and put c at end position if defined
  660. function shiftL(start, end, c) {
  661. while (!isMask(start) && start - 1 >= 0) start--;
  662. for (var i = start; i < end && i < getMaskLength(); i++) {
  663. if (isMask(i)) {
  664. SetReTargetPlaceHolder(buffer, i);
  665. var j = seekNext(buffer, i);
  666. var p = getBufferElement(buffer, j);
  667. if (p != getPlaceHolder(j)) {
  668. if (j < getMaskLength() && isValid(i, p, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def) {
  669. setBufferElement(buffer, i, getBufferElement(buffer, j));
  670. SetReTargetPlaceHolder(buffer, j); //cleanup next position
  671. } else {
  672. if (isMask(i))
  673. break;
  674. }
  675. } else if (c == undefined) break;
  676. } else {
  677. SetReTargetPlaceHolder(buffer, i);
  678. }
  679. }
  680. if (c != undefined)
  681. setBufferElement(buffer, isRTL ? end : seekPrevious(buffer, end), c);
  682. buffer = TruncateInput(buffer.join(''), isRTL).split('');
  683. if (buffer.length == 0) buffer = _buffer.slice();
  684. return start; //return the used start position
  685. }
  686. function shiftR(start, end, c, full) { //full => behave like a push right ~ do not stop on placeholders
  687. for (var i = start; i <= end && i < getMaskLength(); i++) {
  688. if (isMask(i)) {
  689. var t = getBufferElement(buffer, i);
  690. setBufferElement(buffer, i, c);
  691. if (t != getPlaceHolder(i)) {
  692. var j = seekNext(buffer, i);
  693. if (j < getMaskLength()) {
  694. if (isValid(j, t, buffer, true) !== false && tests[determineTestPosition(i)].def == tests[determineTestPosition(j)].def)
  695. c = t;
  696. else {
  697. if (isMask(j))
  698. break;
  699. else c = t;
  700. }
  701. } else break;
  702. } else if (full !== true) break;
  703. } else
  704. SetReTargetPlaceHolder(buffer, i);
  705. }
  706. var lengthBefore = buffer.length;
  707. buffer = TruncateInput(buffer.join(''), isRTL).split('');
  708. if (buffer.length == 0) buffer = _buffer.slice();
  709. return end - (lengthBefore - buffer.length); //return new start position
  710. };
  711. function keydownEvent(e) {
  712. //Safari 5.1.x - modal dialog fires keypress twice workaround
  713. skipKeyPressEvent = false;
  714. var input = this, k = e.keyCode, pos = caret(input);
  715. //set input direction according the position to the radixPoint
  716. if (opts.numericInput) {
  717. var nptStr = input._valueGet();
  718. var radixPosition = nptStr.indexOf(opts.radixPoint[opts.radixPoint.length - 1]);
  719. if (radixPosition != -1) {
  720. isRTL = pos.end <= radixPosition;
  721. }
  722. }
  723. //backspace, delete, and escape get special treatment
  724. if (k == opts.keyCode.BACKSPACE || k == opts.keyCode.DELETE || (iphone && k == 127)) {//backspace/delete
  725. var maskL = getMaskLength();
  726. if (pos.begin == 0 && pos.end == maskL) {
  727. buffer = _buffer.slice();
  728. writeBuffer(input, buffer);
  729. if (!isRTL) caret(input, firstMaskPos);
  730. } else if ((pos.end - pos.begin) > 1 || ((pos.end - pos.begin) == 1 && opts.insertMode)) { //FIXME not yet complete
  731. clearBuffer(buffer, pos.begin, pos.end);
  732. writeBuffer(input, buffer, beginPos);
  733. } else {
  734. var beginPos = pos.begin - (k == opts.keyCode.DELETE ? 0 : 1);
  735. if (beginPos < firstMaskPos && k == opts.keyCode.DELETE) {
  736. beginPos = firstMaskPos;
  737. }
  738. if (beginPos >= firstMaskPos) {
  739. if (opts.numericInput && opts.greedy && k == opts.keyCode.DELETE && buffer[beginPos] == opts.radixPoint[opts.radixPoint.length - 1]) {
  740. beginPos = seekNext(buffer, beginPos);
  741. isRTL = false;
  742. }
  743. if (isRTL) {
  744. beginPos = shiftR(firstMaskPos, beginPos, getPlaceHolder(beginPos), true);
  745. beginPos = (opts.numericInput && opts.greedy && k == opts.keyCode.BACKSPACE && buffer[beginPos + 1] == opts.radixPoint[opts.radixPoint.length - 1]) ? beginPos + 1 : seekNext(buffer, beginPos);
  746. } else beginPos = shiftL(beginPos, maskL);
  747. writeBuffer(input, buffer, beginPos);
  748. }
  749. }
  750. if (opts.oncleared && input._valueGet() == _buffer.join(''))
  751. opts.oncleared.call(input);
  752. return false;
  753. } else if (k == opts.keyCode.END || k == opts.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  754. setTimeout(function() {
  755. var caretPos = checkVal(input, buffer, false, true);
  756. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  757. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  758. }, 0);
  759. return false;
  760. } else if (k == opts.keyCode.HOME || k == opts.keyCode.PAGE_UP) {//Home or page_up
  761. caret(input, 0, e.shiftKey ? pos.begin : 0);
  762. return false;
  763. }
  764. else if (k == opts.keyCode.ESCAPE) {//escape
  765. input._valueSet(undoBuffer);
  766. caret(input, 0, checkVal(input, buffer));
  767. return false;
  768. } else if (k == opts.keyCode.INSERT) {//insert
  769. opts.insertMode = !opts.insertMode;
  770. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  771. return false;
  772. } else if (e.ctrlKey && k == 88) {
  773. setTimeout(function() {
  774. caret(input, checkVal(input, buffer, true));
  775. }, 0);
  776. } else if (opts.numericInput && e['char'] == opts.radixPoint[opts.radixPoint.length - 1]) {
  777. var nptStr = input._valueGet();
  778. var radixPosition = nptStr.indexOf(opts.radixPoint[opts.radixPoint.length - 1]);
  779. caret(input, seekNext(buffer, radixPosition != -1 ? radixPosition : getMaskLength()));
  780. }
  781. else if (!opts.insertMode) { //overwritemode
  782. if (k == opts.keyCode.RIGHT) {//right
  783. var caretPos = pos.begin == pos.end ? pos.end + 1 : pos.end;
  784. caretPos = caretPos < getMaskLength() ? caretPos : pos.end;
  785. caret(input, e.shiftKey ? pos.begin : caretPos, e.shiftKey ? caretPos + 1 : caretPos);
  786. return false;
  787. } else if (k == opts.keyCode.LEFT) {//left
  788. var caretPos = pos.begin - 1;
  789. caretPos = caretPos > 0 ? caretPos : 0;
  790. caret(input, caretPos, e.shiftKey ? pos.end : caretPos);
  791. return false;
  792. }
  793. }
  794. opts.onKeyDown.call(this, e, opts); //extra stuff todo on keydown
  795. ignorable = $.inArray(k, opts.ignorables) != -1;
  796. }
  797. function keypressEvent(e) {
  798. //Safari 5.1.x - modal dialog fires keypress twice workaround
  799. if (skipKeyPressEvent) return false;
  800. skipKeyPressEvent = true;
  801. var input = this;
  802. e = e || window.event;
  803. var k = e.which || e.charCode || e.keyCode;
  804. if (e.ctrlKey || e.altKey || e.metaKey || ignorable) {//Ignore
  805. return true;
  806. } else {
  807. if (k) {
  808. var pos = caret(input), c = String.fromCharCode(k), maskL = getMaskLength();
  809. if (isRTL) {
  810. var p = opts.numericInput ? pos.end : seekPrevious(buffer, pos.end), np;
  811. if ((np = isValid(p == maskL || getBufferElement(buffer, p) == opts.radixPoint[opts.radixPoint.length - 1] ? seekPrevious(buffer, p) : p, c, buffer, false)) !== false) {
  812. if (np !== true) p = np; //set new position from isValid
  813. if (isValid(firstMaskPos, buffer[firstMaskPos], buffer, true) == false || (opts.greedy === false && buffer.length < maskL)) {
  814. if (buffer[firstMaskPos] != getPlaceHolder(firstMaskPos) && buffer.length < maskL) {
  815. var offset = prepareBuffer(buffer, -1, isRTL);
  816. if (pos.end != 0) p = p + offset;
  817. maskL = buffer.length;
  818. }
  819. shiftL(firstMaskPos, opts.numericInput ? seekPrevious(buffer, p) : p, c);
  820. writeBuffer(input, buffer, opts.numericInput && p == 0 ? seekNext(buffer, p) : p);
  821. } else if (opts.oncomplete)
  822. opts.oncomplete.call(input);
  823. } else if (android) writeBuffer(input, buffer, pos.begin);
  824. }
  825. else {
  826. var p = seekNext(buffer, pos.begin - 1), np;
  827. prepareBuffer(buffer, p, isRTL);
  828. if ((np = isValid(p, c, buffer, false)) !== false) {
  829. if (np !== true) p = np; //set new position from isValid
  830. if (opts.insertMode == true) shiftR(p, buffer.length, c); else setBufferElement(buffer, p, c);
  831. var next = seekNext(buffer, p);
  832. writeBuffer(input, buffer, next);
  833. if (opts.oncomplete && next == maskL)
  834. opts.oncomplete.call(input);
  835. } else if (android) writeBuffer(input, buffer, pos.begin);
  836. }
  837. return false;
  838. }
  839. }
  840. }
  841. function keyupEvent(e) {
  842. var $input = $(this), input = this;
  843. var k = e.keyCode;
  844. opts.onKeyUp.call(this, e, opts); //extra stuff todo on keyup
  845. if (k == opts.keyCode.TAB && $input.hasClass('focus.inputmask') && input._valueGet().length == 0) {
  846. buffer = _buffer.slice();
  847. writeBuffer(input, buffer);
  848. if (!isRTL) caret(input, 0);
  849. undoBuffer = input._valueGet();
  850. }
  851. }
  852. }
  853. };
  854. }
  855. })(jQuery);