jquery.inputmask.js 56 KB

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