jquery.inputmask.js 57 KB

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