jquery.inputmask.js 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595
  1. /*
  2. * Input Mask plugin for jquery
  3. * http://github.com/RobinHerbots/jquery.inputmask
  4. * Copyright (c) 2010 - Robin Herbots
  5. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. * Version: 0.0.0-dev
  7. */
  8. (function ($) {
  9. if ($.fn.inputmask === undefined) {
  10. function inputmask(options) {
  11. //init options
  12. this.opts = $.extend(true, {}, this.defaults, options);
  13. this.noMasksCache = options && options.definitions !== undefined;
  14. resolveAlias(this.opts.alias, options, this.opts);
  15. }
  16. inputmask.prototype = {
  17. //options default
  18. defaults: {
  19. placeholder: "_",
  20. optionalmarker: {
  21. start: "[",
  22. end: "]"
  23. },
  24. quantifiermarker: {
  25. start: "{",
  26. end: "}"
  27. },
  28. groupmarker: {
  29. start: "(",
  30. end: ")"
  31. },
  32. alternatormarker: "|",
  33. escapeChar: "\\",
  34. mask: null,
  35. oncomplete: $.noop, //executes when the mask is complete
  36. onincomplete: $.noop, //executes when the mask is incomplete and focus is lost
  37. oncleared: $.noop, //executes when the mask is cleared
  38. repeat: 0, //repetitions of the mask: * ~ forever, otherwise specify an integer
  39. greedy: true, //true: allocated buffer for the mask and repetitions - false: allocate only if needed
  40. autoUnmask: false, //automatically unmask when retrieving the value with $.fn.val or value if the browser supports __lookupGetter__ or getOwnPropertyDescriptor
  41. removeMaskOnSubmit: false, //remove the mask before submitting the form.
  42. clearMaskOnLostFocus: true,
  43. insertMode: true, //insert the input or overwrite the input
  44. clearIncomplete: false, //clear the incomplete input on blur
  45. aliases: {}, //aliases definitions => see jquery.inputmask.extensions.js
  46. alias: null,
  47. onKeyDown: $.noop, //callback to implement autocomplete on certain keys for example. args => event, buffer, caretPos, opts
  48. onBeforeMask: undefined, //executes before masking the initial value to allow preprocessing of the initial value. args => initialValue, opts => return processedValue
  49. onBeforePaste: undefined, //executes before masking the pasted value to allow preprocessing of the pasted value. args => pastedValue, opts => return processedValue
  50. onBeforeWrite: undefined, //executes before writing to the masked element. args => event, opts
  51. onUnMask: undefined, //executes after unmasking to allow postprocessing of the unmaskedvalue. args => maskedValue, unmaskedValue, opts
  52. showMaskOnFocus: true, //show the mask-placeholder when the input has focus
  53. showMaskOnHover: true, //show the mask-placeholder when hovering the empty input
  54. onKeyValidation: $.noop, //executes on every key-press with the result of isValid. Params: result, opts
  55. skipOptionalPartCharacter: " ", //a character which can be used to skip an optional part of a mask
  56. showTooltip: false, //show the activemask as tooltip
  57. numericInput: false, //numericInput input direction style (input shifts to the left while holding the caret position)
  58. rightAlign: false, //align to the right
  59. undoOnEscape: true, //pressing escape reverts the value to the value before focus
  60. //numeric basic properties
  61. radixPoint: "", //".", // | ","
  62. radixFocus: false, //position caret to radixpoint on initial click
  63. //numeric basic properties
  64. nojumps: false, //do not jump over fixed parts in the mask
  65. nojumpsThreshold: 0, //start nojumps as of
  66. keepStatic: undefined, //try to keep the mask static while typing. Decisions to alter the mask will be posponed if possible - undefined see auto selection for multi masks
  67. definitions: {
  68. '9': {
  69. validator: "[0-9]",
  70. cardinality: 1,
  71. definitionSymbol: "*"
  72. },
  73. 'a': {
  74. validator: "[A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  75. cardinality: 1,
  76. definitionSymbol: "*"
  77. },
  78. '*': {
  79. validator: "[0-9A-Za-z\u0410-\u044F\u0401\u0451\u00C0-\u00FF\u00B5]",
  80. cardinality: 1
  81. }
  82. },
  83. //specify keyCodes which should not be considered in the keypress event, otherwise the preventDefault will stop their default behavior especially in FF
  84. ignorables: [8, 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],
  85. isComplete: undefined, //override for isComplete - args => buffer, opts - return true || false
  86. canClearPosition: $.noop, //hook to alter the clear behavior in the stripValidPositions args => maskset, position, lastValidPosition, opts => return true|false
  87. postValidation: undefined //hook to postValidate the result from isValid. Usefull for validating the entry as a whole. args => buffer, opts => return true/false
  88. },
  89. keyCode: {
  90. ALT: 18,
  91. BACKSPACE: 8,
  92. CAPS_LOCK: 20,
  93. COMMA: 188,
  94. COMMAND: 91,
  95. COMMAND_LEFT: 91,
  96. COMMAND_RIGHT: 93,
  97. CONTROL: 17,
  98. DELETE: 46,
  99. DOWN: 40,
  100. END: 35,
  101. ENTER: 13,
  102. ESCAPE: 27,
  103. HOME: 36,
  104. INSERT: 45,
  105. LEFT: 37,
  106. MENU: 93,
  107. NUMPAD_ADD: 107,
  108. NUMPAD_DECIMAL: 110,
  109. NUMPAD_DIVIDE: 111,
  110. NUMPAD_ENTER: 108,
  111. NUMPAD_MULTIPLY: 106,
  112. NUMPAD_SUBTRACT: 109,
  113. PAGE_DOWN: 34,
  114. PAGE_UP: 33,
  115. PERIOD: 190,
  116. RIGHT: 39,
  117. SHIFT: 16,
  118. SPACE: 32,
  119. TAB: 9,
  120. UP: 38,
  121. WINDOWS: 91
  122. },
  123. masksCache: {},
  124. escapeRegex: function (str) {
  125. var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^'];
  126. return str.replace(new RegExp('(\\' + specials.join('|\\') + ')', 'gim'), '\\$1');
  127. },
  128. format: function (value, options, metadata) {
  129. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  130. resolveAlias(opts.alias, options, opts);
  131. return maskScope({
  132. "action": "format",
  133. "value": value,
  134. "metadata": metadata
  135. }, generateMaskSet(opts, options && options.definitions !== undefined), opts);
  136. },
  137. isValid: function (value, options) {
  138. var opts = $.extend(true, {}, $.inputmask.defaults, options);
  139. resolveAlias(opts.alias, options, opts);
  140. return maskScope({
  141. "action": "isValid",
  142. "value": value
  143. }, generateMaskSet(opts, options && options.definitions !== undefined), opts);
  144. },
  145. }
  146. //helper functions
  147. function isInputEventSupported(eventName) {
  148. var el = document.createElement('input'),
  149. evName = 'on' + eventName,
  150. isSupported = (evName in el);
  151. if (!isSupported) {
  152. el.setAttribute(evName, 'return;');
  153. isSupported = typeof el[evName] == 'function';
  154. }
  155. el = null;
  156. return isSupported;
  157. }
  158. function isInputTypeSupported(inputType) {
  159. var isSupported = inputType == "text" || inputType == "tel" || inputType == "password";
  160. if (!isSupported) {
  161. var el = document.createElement('input');
  162. el.setAttribute("type", inputType);
  163. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  164. el = null;
  165. }
  166. return isSupported;
  167. }
  168. function resolveAlias(aliasStr, options, opts) {
  169. var aliasDefinition = opts.aliases[aliasStr];
  170. if (aliasDefinition) {
  171. if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts); //alias is another alias
  172. $.extend(true, opts, aliasDefinition); //merge alias definition in the options
  173. $.extend(true, opts, options); //reapply extra given options
  174. return true;
  175. }
  176. return false;
  177. }
  178. function generateMaskSet(opts, nocache) {
  179. var ms = undefined;
  180. function analyseMask(mask) {
  181. var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g,
  182. escaped = false;
  183. function maskToken(isGroup, isOptional, isQuantifier, isAlternator) {
  184. this.matches = [];
  185. this.isGroup = isGroup || false;
  186. this.isOptional = isOptional || false;
  187. this.isQuantifier = isQuantifier || false;
  188. this.isAlternator = isAlternator || false;
  189. this.quantifier = {
  190. min: 1,
  191. max: 1
  192. };
  193. };
  194. //test definition => {fn: RegExp/function, cardinality: int, optionality: bool, newBlockMarker: bool, casing: null/upper/lower, def: definitionSymbol, placeholder: placeholder, mask: real maskDefinition}
  195. function insertTestDefinition(mtoken, element, position) {
  196. var maskdef = opts.definitions[element];
  197. var newBlockMarker = mtoken.matches.length == 0;
  198. position = position != undefined ? position : mtoken.matches.length;
  199. if (maskdef && !escaped) {
  200. maskdef["placeholder"] = $.isFunction(maskdef["placeholder"]) ? maskdef["placeholder"].call(this, opts) : maskdef["placeholder"];
  201. var prevalidators = maskdef["prevalidator"],
  202. prevalidatorsL = prevalidators ? prevalidators.length : 0;
  203. for (var i = 1; i < maskdef.cardinality; i++) {
  204. var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [],
  205. validator = prevalidator["validator"],
  206. cardinality = prevalidator["cardinality"];
  207. mtoken.matches.splice(position++, 0, {
  208. fn: validator ? typeof validator == 'string' ? new RegExp(validator) : new function () {
  209. this.test = validator;
  210. } : new RegExp("."),
  211. cardinality: cardinality ? cardinality : 1,
  212. optionality: mtoken.isOptional,
  213. newBlockMarker: newBlockMarker,
  214. casing: maskdef["casing"],
  215. def: maskdef["definitionSymbol"] || element,
  216. placeholder: maskdef["placeholder"],
  217. mask: element
  218. });
  219. }
  220. mtoken.matches.splice(position++, 0, {
  221. fn: maskdef.validator ? typeof maskdef.validator == 'string' ? new RegExp(maskdef.validator) : new function () {
  222. this.test = maskdef.validator;
  223. } : new RegExp("."),
  224. cardinality: maskdef.cardinality,
  225. optionality: mtoken.isOptional,
  226. newBlockMarker: newBlockMarker,
  227. casing: maskdef["casing"],
  228. def: maskdef["definitionSymbol"] || element,
  229. placeholder: maskdef["placeholder"],
  230. mask: element
  231. });
  232. } else {
  233. mtoken.matches.splice(position++, 0, {
  234. fn: null,
  235. cardinality: 0,
  236. optionality: mtoken.isOptional,
  237. newBlockMarker: newBlockMarker,
  238. casing: null,
  239. def: element,
  240. placeholder: undefined,
  241. mask: element
  242. });
  243. escaped = false;
  244. }
  245. }
  246. var currentToken = new maskToken(),
  247. match,
  248. m,
  249. openenings = [],
  250. maskTokens = [],
  251. openingToken,
  252. currentOpeningToken,
  253. alternator,
  254. lastMatch;
  255. while (match = tokenizer.exec(mask)) {
  256. m = match[0];
  257. switch (m.charAt(0)) {
  258. case opts.optionalmarker.end:
  259. // optional closing
  260. case opts.groupmarker.end:
  261. // Group closing
  262. openingToken = openenings.pop();
  263. if (openenings.length > 0) {
  264. currentOpeningToken = openenings[openenings.length - 1];
  265. currentOpeningToken["matches"].push(openingToken);
  266. if (currentOpeningToken.isAlternator) { //handle alternator (a) | (b) case
  267. alternator = openenings.pop();
  268. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  269. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  270. }
  271. if (openenings.length > 0) {
  272. currentOpeningToken = openenings[openenings.length - 1];
  273. currentOpeningToken["matches"].push(alternator);
  274. } else {
  275. currentToken.matches.push(alternator);
  276. }
  277. }
  278. } else {
  279. currentToken.matches.push(openingToken);
  280. }
  281. break;
  282. case opts.optionalmarker.start:
  283. // optional opening
  284. openenings.push(new maskToken(false, true));
  285. break;
  286. case opts.groupmarker.start:
  287. // Group opening
  288. openenings.push(new maskToken(true));
  289. break;
  290. case opts.quantifiermarker.start:
  291. //Quantifier
  292. var quantifier = new maskToken(false, false, true);
  293. m = m.replace(/[{}]/g, "");
  294. var mq = m.split(","),
  295. mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]),
  296. mq1 = mq.length == 1 ? mq0 : (isNaN(mq[1]) ? mq[1] : parseInt(mq[1]));
  297. if (mq1 == "*" || mq1 == "+") {
  298. mq0 = mq1 == "*" ? 0 : 1;
  299. }
  300. quantifier.quantifier = {
  301. min: mq0,
  302. max: mq1
  303. };
  304. if (openenings.length > 0) {
  305. var matches = openenings[openenings.length - 1]["matches"];
  306. match = matches.pop();
  307. if (!match["isGroup"]) {
  308. var groupToken = new maskToken(true);
  309. groupToken.matches.push(match);
  310. match = groupToken;
  311. }
  312. matches.push(match);
  313. matches.push(quantifier);
  314. } else {
  315. match = currentToken.matches.pop();
  316. if (!match["isGroup"]) {
  317. var groupToken = new maskToken(true);
  318. groupToken.matches.push(match);
  319. match = groupToken;
  320. }
  321. currentToken.matches.push(match);
  322. currentToken.matches.push(quantifier);
  323. }
  324. break;
  325. case opts.escapeChar:
  326. escaped = true;
  327. break;
  328. case opts.alternatormarker:
  329. if (openenings.length > 0) {
  330. currentOpeningToken = openenings[openenings.length - 1];
  331. lastMatch = currentOpeningToken.matches.pop();
  332. } else {
  333. lastMatch = currentToken.matches.pop();
  334. }
  335. if (lastMatch.isAlternator) {
  336. openenings.push(lastMatch);
  337. } else {
  338. alternator = new maskToken(false, false, false, true);
  339. alternator.matches.push(lastMatch);
  340. openenings.push(alternator);
  341. }
  342. break;
  343. default:
  344. if (openenings.length > 0) {
  345. currentOpeningToken = openenings[openenings.length - 1];
  346. if (currentOpeningToken.matches.length > 0 && !currentOpeningToken.isAlternator) {
  347. lastMatch = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
  348. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  349. lastMatch.isGroup = false;
  350. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  351. insertTestDefinition(lastMatch, opts.groupmarker.end);
  352. }
  353. }
  354. insertTestDefinition(currentOpeningToken, m);
  355. if (currentOpeningToken.isAlternator) { //handle alternator a | b case
  356. alternator = openenings.pop();
  357. for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
  358. alternator.matches[mndx].isGroup = false; //don't mark alternate groups as group
  359. }
  360. if (openenings.length > 0) {
  361. currentOpeningToken = openenings[openenings.length - 1];
  362. currentOpeningToken["matches"].push(alternator);
  363. } else {
  364. currentToken.matches.push(alternator);
  365. }
  366. }
  367. } else {
  368. if (currentToken.matches.length > 0) {
  369. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  370. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  371. lastMatch.isGroup = false;
  372. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  373. insertTestDefinition(lastMatch, opts.groupmarker.end);
  374. }
  375. }
  376. insertTestDefinition(currentToken, m);
  377. }
  378. }
  379. }
  380. if (currentToken.matches.length > 0) {
  381. lastMatch = currentToken.matches[currentToken.matches.length - 1];
  382. if (lastMatch["isGroup"]) { //this is not a group but a normal mask => convert
  383. lastMatch.isGroup = false;
  384. insertTestDefinition(lastMatch, opts.groupmarker.start, 0);
  385. insertTestDefinition(lastMatch, opts.groupmarker.end);
  386. }
  387. maskTokens.push(currentToken);
  388. }
  389. //console.log(JSON.stringify(maskTokens));
  390. return maskTokens;
  391. }
  392. function generateMask(mask, metadata) {
  393. if (mask == undefined || mask == "")
  394. return undefined;
  395. else {
  396. if (mask.length == 1 && opts.greedy == false && opts.repeat != 0) {
  397. opts.placeholder = "";
  398. } //hide placeholder with single non-greedy mask
  399. if (opts.repeat > 0 || opts.repeat == "*" || opts.repeat == "+") {
  400. var repeatStart = opts.repeat == "*" ? 0 : (opts.repeat == "+" ? 1 : opts.repeat);
  401. mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end;
  402. }
  403. var masksetDefinition;
  404. if ($.inputmask.masksCache[mask] == undefined || nocache === true) {
  405. masksetDefinition = {
  406. "mask": mask,
  407. "maskToken": analyseMask(mask),
  408. "validPositions": {},
  409. "_buffer": undefined,
  410. "buffer": undefined,
  411. "tests": {},
  412. "metadata": metadata
  413. };
  414. if (nocache !== true)
  415. $.inputmask.masksCache[mask] = masksetDefinition;
  416. } else masksetDefinition = $.extend(true, {}, $.inputmask.masksCache[mask]);
  417. return masksetDefinition;
  418. }
  419. }
  420. function preProcessMask(mask) {
  421. mask = mask.toString();
  422. if (opts.numericInput) { //TODO FIX FOR DYNAMIC MASKS WITH QUANTIFIERS
  423. mask = mask.split('').reverse();
  424. for (var ndx = 0; ndx < mask.length; ndx++) {
  425. if (mask[ndx] == opts.optionalmarker.start)
  426. mask[ndx] = opts.optionalmarker.end;
  427. else if (mask[ndx] == opts.optionalmarker.end)
  428. mask[ndx] = opts.optionalmarker.start;
  429. else if (mask[ndx] == opts.groupmarker.start)
  430. mask[ndx] = opts.groupmarker.end;
  431. else if (mask[ndx] == opts.groupmarker.end)
  432. mask[ndx] = opts.groupmarker.start;
  433. }
  434. mask = mask.join('');
  435. }
  436. return mask;
  437. }
  438. if ($.isFunction(opts.mask)) { //allow mask to be a preprocessing fn - should return a valid mask
  439. opts.mask = opts.mask.call(this, opts);
  440. }
  441. if ($.isArray(opts.mask)) {
  442. if (opts.mask.length > 1) {
  443. opts.keepStatic = opts.keepStatic == undefined ? true : opts.keepStatic; //enable by default when passing multiple masks when the option is not explicitly specified
  444. var altMask = "(";
  445. $.each(opts.mask, function (ndx, msk) {
  446. if (altMask.length > 1)
  447. altMask += ")|(";
  448. if (msk["mask"] != undefined && !$.isFunction(msk["mask"])) {
  449. altMask += preProcessMask(msk["mask"]);
  450. } else {
  451. altMask += preProcessMask(msk);
  452. }
  453. });
  454. altMask += ")";
  455. return generateMask(altMask, opts.mask);
  456. } else opts.mask = opts.mask.pop();
  457. }
  458. if (opts.mask) {
  459. if (opts.mask["mask"] != undefined && !$.isFunction(opts.mask["mask"])) {
  460. ms = generateMask(preProcessMask(opts.mask["mask"]), opts.mask);
  461. } else {
  462. ms = generateMask(preProcessMask(opts.mask), opts.mask);
  463. }
  464. }
  465. return ms;
  466. }
  467. var ua = navigator.userAgent,
  468. iphone = ua.match(new RegExp("iphone", "i")) !== null,
  469. android = ua.match(new RegExp("android.*safari.*", "i")) !== null,
  470. androidchrome = ua.match(new RegExp("android.*chrome.*", "i")) !== null,
  471. androidfirefox = ua.match(new RegExp("android.*firefox.*", "i")) !== null,
  472. kindle = /Kindle/i.test(ua) || /Silk/i.test(ua) || /KFTT/i.test(ua) || /KFOT/i.test(ua) || /KFJWA/i.test(ua) || /KFJWI/i.test(ua) || /KFSOWI/i.test(ua) || /KFTHWA/i.test(ua) || /KFTHWI/i.test(ua) || /KFAPWA/i.test(ua) || /KFAPWI/i.test(ua),
  473. PasteEventType = isInputEventSupported('paste') ? 'paste' : isInputEventSupported('input') ? 'input' : "propertychange";
  474. //if (androidchrome) {
  475. // var browser = navigator.userAgent.match(new RegExp("chrome.*", "i")),
  476. // version = parseInt(new RegExp(/[0-9]+/).exec(browser));
  477. // androidchrome32 = (version == 32);
  478. //}
  479. //masking scope
  480. //actionObj definition see below
  481. function maskScope(actionObj, maskset, opts) {
  482. var isRTL = false,
  483. undoValue,
  484. compositionValidPos,
  485. compositionCaretPos,
  486. compositionData,
  487. $el,
  488. skipKeyPressEvent = false, //Safari 5.1.x - modal dialog fires keypress twice workaround
  489. skipInputEvent = false, //skip when triggered from within inputmask
  490. ignorable = false,
  491. maxLength,
  492. firstClick = true;
  493. //maskset helperfunctions
  494. function getMaskTemplate(baseOnInput, minimalPos, includeInput) {
  495. minimalPos = minimalPos || 0;
  496. var maskTemplate = [],
  497. ndxIntlzr, pos = 0,
  498. test, testPos;
  499. do {
  500. if (baseOnInput === true && getMaskSet()['validPositions'][pos]) {
  501. var validPos = getMaskSet()['validPositions'][pos];
  502. test = validPos["match"];
  503. ndxIntlzr = validPos["locator"].slice();
  504. maskTemplate.push(includeInput === true ? validPos["input"] : getPlaceholder(pos, test));
  505. } else {
  506. //console.log("getmasktemplate " + pos + " " + JSON.stringify(ndxIntlzr));
  507. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  508. test = testPos["match"];
  509. ndxIntlzr = testPos["locator"].slice();
  510. maskTemplate.push(getPlaceholder(pos, test));
  511. }
  512. pos++;
  513. } while ((maxLength == undefined || pos - 1 < maxLength) && test["fn"] != null || (test["fn"] == null && test["def"] != "") || minimalPos >= pos);
  514. maskTemplate.pop(); //drop the last one which is empty
  515. return maskTemplate;
  516. }
  517. function getMaskSet() {
  518. return maskset;
  519. }
  520. function resetMaskSet(soft) {
  521. var maskset = getMaskSet();
  522. maskset["buffer"] = undefined;
  523. maskset["tests"] = {};
  524. if (soft !== true) {
  525. maskset["_buffer"] = undefined;
  526. maskset["validPositions"] = {};
  527. maskset["p"] = 0;
  528. }
  529. }
  530. function getLastValidPosition(closestTo, strict) {
  531. var maskset = getMaskSet(),
  532. lastValidPosition = -1,
  533. valids = maskset["validPositions"];
  534. if (closestTo == undefined) closestTo = -1;
  535. var before = lastValidPosition,
  536. after = lastValidPosition;
  537. for (var posNdx in valids) {
  538. var psNdx = parseInt(posNdx);
  539. if (valids[psNdx] && (strict || valids[psNdx]["match"].fn != null)) {
  540. if (psNdx <= closestTo) before = psNdx;
  541. if (psNdx >= closestTo) after = psNdx;
  542. }
  543. }
  544. lastValidPosition = (before != -1 && (closestTo - before) > 1) || after < closestTo ? before : after;
  545. return lastValidPosition;
  546. }
  547. function setValidPosition(pos, validTest, fromSetValid) {
  548. if (opts.insertMode && getMaskSet()["validPositions"][pos] != undefined && fromSetValid == undefined) {
  549. //reposition & revalidate others
  550. var positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]),
  551. lvp = getLastValidPosition(),
  552. i;
  553. for (i = pos; i <= lvp; i++) { //clear selection
  554. delete getMaskSet()["validPositions"][i];
  555. }
  556. getMaskSet()["validPositions"][pos] = validTest;
  557. var valid = true,
  558. j, vps = getMaskSet()["validPositions"];
  559. for (i = (j = pos) ; i <= lvp; i++) {
  560. var t = positionsClone[i];
  561. if (t != undefined) {
  562. var posMatch = j,
  563. prevPosMatch = -1;
  564. while (posMatch < getMaskLength() && ((t.match.fn == null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  565. //determine next position
  566. if (t.match.fn == null || (!opts.keepStatic && vps[i] && (vps[i + 1] != undefined && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || vps[i].alternation != undefined)))
  567. posMatch++;
  568. else
  569. posMatch = seekNext(j);
  570. //does it match
  571. if (positionCanMatchDefinition(posMatch, t["match"].def)) {
  572. valid = isValid(posMatch, t["input"], true, true) !== false;
  573. j = posMatch;
  574. break;
  575. } else {
  576. valid = t["match"].fn == null;
  577. if (prevPosMatch == posMatch) break; //prevent endless loop
  578. prevPosMatch = posMatch;
  579. }
  580. }
  581. }
  582. if (!valid) break;
  583. }
  584. if (!valid) {
  585. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  586. return false;
  587. }
  588. } else
  589. getMaskSet()["validPositions"][pos] = validTest;
  590. return true;
  591. }
  592. function stripValidPositions(start, end, nocheck, strict) {
  593. var i, startPos = start;
  594. getMaskSet()["p"] = start; //needed for alternated position after overtype selection
  595. var endPos = end;
  596. for (i = startPos; i < end; i++) { //clear selection
  597. if (getMaskSet()["validPositions"][i] != undefined) {
  598. if (nocheck === true || opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) != false)
  599. delete getMaskSet()["validPositions"][i];
  600. }
  601. }
  602. resetMaskSet(true);
  603. for (i = startPos + 1; i <= getLastValidPosition() ;) {
  604. while (getMaskSet()["validPositions"][startPos] != undefined) startPos++;
  605. var s = getMaskSet()["validPositions"][startPos];
  606. if (i < startPos) i = startPos + 1;
  607. var t = getMaskSet()["validPositions"][i];
  608. if (t != undefined && s == undefined) {
  609. if (positionCanMatchDefinition(startPos, t.match.def) && isValid(startPos, t["input"], true) !== false) {
  610. delete getMaskSet()["validPositions"][i];
  611. i++;
  612. }
  613. startPos++;
  614. } else i++;
  615. }
  616. //remove radixpoint if needed
  617. var lvp = getLastValidPosition(),
  618. ml = getMaskLength();
  619. if (getMaskSet()["validPositions"][lvp] != undefined && getMaskSet()["validPositions"][lvp].input == opts.radixPoint)
  620. delete getMaskSet()["validPositions"][lvp];
  621. for (i = lvp + 1; i <= ml; i++) {
  622. if (getMaskSet()["validPositions"][i])
  623. delete getMaskSet()["validPositions"][i];
  624. }
  625. resetMaskSet(true);
  626. }
  627. function getTestTemplate(pos, ndxIntlzr, tstPs) {
  628. var testPos = getMaskSet()["validPositions"][pos];
  629. if (testPos == undefined) {
  630. var testPositions = getTests(pos, ndxIntlzr, tstPs),
  631. lvp = getLastValidPosition(),
  632. lvTest = getMaskSet()["validPositions"][lvp] || getTests(0)[0],
  633. lvTestAltArr = (lvTest.alternation != undefined) ? lvTest["locator"][lvTest.alternation].toString().split(',') : [];
  634. for (var ndx = 0; ndx < testPositions.length; ndx++) {
  635. testPos = testPositions[ndx];
  636. if (testPos["match"] &&
  637. (((opts.greedy && testPos["match"].optionalQuantifier !== true) || (testPos["match"].optionality === false || testPos["match"].newBlockMarker === false) && testPos["match"].optionalQuantifier !== true) &&
  638. ((lvTest.alternation == undefined || lvTest.alternation != testPos.alternation) ||
  639. (testPos["locator"][lvTest.alternation] != undefined && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr))))) {
  640. break;
  641. }
  642. }
  643. }
  644. return testPos;
  645. }
  646. function getTest(pos) {
  647. if (getMaskSet()['validPositions'][pos]) {
  648. return getMaskSet()['validPositions'][pos]["match"];
  649. }
  650. return getTests(pos)[0]["match"];
  651. }
  652. function positionCanMatchDefinition(pos, def) {
  653. var valid = false,
  654. tests = getTests(pos);
  655. for (var tndx = 0; tndx < tests.length; tndx++) {
  656. if (tests[tndx]["match"] && tests[tndx]["match"].def == def) {
  657. valid = true;
  658. break;
  659. }
  660. }
  661. return valid;
  662. };
  663. function getTests(pos, ndxIntlzr, tstPs, cacheable) {
  664. var maskTokens = getMaskSet()["maskToken"],
  665. testPos = ndxIntlzr ? tstPs : 0,
  666. ndxInitializer = ndxIntlzr || [0],
  667. matches = [],
  668. insertStop = false;
  669. function ResolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { //ndxInitilizer contains a set of indexes to speedup searches in the mtokens
  670. function handleMatch(match, loopNdx, quantifierRecurse) {
  671. if (testPos > 10000) {
  672. alert("jquery.inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet()["mask"]);
  673. return true;
  674. }
  675. if (testPos == pos && match.matches == undefined) {
  676. matches.push({
  677. "match": match,
  678. "locator": loopNdx.reverse()
  679. });
  680. return true;
  681. } else if (match.matches != undefined) {
  682. if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier
  683. match = handleMatch(maskToken.matches[tndx + 1], loopNdx);
  684. if (match) return true;
  685. } else if (match.isOptional) {
  686. var optionalToken = match;
  687. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  688. if (match) {
  689. var latestMatch = matches[matches.length - 1]["match"];
  690. var isFirstMatch = $.inArray(latestMatch, optionalToken.matches) == 0;
  691. if (isFirstMatch) {
  692. insertStop = true; //insert a stop
  693. testPos = pos; //match the position after the group
  694. } else return true;
  695. }
  696. } else if (match.isAlternator) {
  697. var alternateToken = match,
  698. malternateMatches = [],
  699. maltMatches,
  700. currentMatches = matches.slice(),
  701. loopNdxCnt = loopNdx.length;
  702. var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
  703. if (altIndex == -1 || typeof altIndex == "string") {
  704. var currentPos = testPos,
  705. ndxInitializerClone = ndxInitializer.slice(),
  706. altIndexArr = [];
  707. if (typeof altIndex == "string") altIndexArr = altIndex.split(",");
  708. for (var amndx = 0; amndx < alternateToken.matches.length; amndx++) {
  709. matches = [];
  710. match = handleMatch(alternateToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;
  711. if (match !== true && match != undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further
  712. var ntndx = maskToken.matches.indexOf(match) + 1;
  713. if (maskToken.matches.length > ntndx) {
  714. match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse)
  715. if (match) {
  716. altIndexArr.push(ntndx.toString());
  717. $.each(matches, function (ndx, lmnt) {
  718. lmnt.alternation = loopNdx.length - 1;
  719. });
  720. }
  721. }
  722. }
  723. maltMatches = matches.slice();
  724. testPos = currentPos;
  725. matches = [];
  726. //cloneback
  727. for (var i = 0; i < ndxInitializerClone.length; i++) {
  728. ndxInitializer[i] = ndxInitializerClone[i];
  729. }
  730. //fuzzy merge matches
  731. for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
  732. var altMatch = maltMatches[ndx1];
  733. altMatch.alternation = altMatch.alternation || loopNdxCnt;
  734. for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
  735. var altMatch2 = malternateMatches[ndx2];
  736. //verify equality
  737. if (altMatch.match.mask == altMatch2.match.mask && (typeof altIndex != "string" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) != -1)) {
  738. maltMatches.splice(ndx1, 1);
  739. ndx1--;
  740. altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation];
  741. altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition
  742. break;
  743. }
  744. }
  745. }
  746. malternateMatches = malternateMatches.concat(maltMatches);
  747. }
  748. if (typeof altIndex == "string") { //filter matches
  749. malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {
  750. if (isFinite(ndx)) {
  751. var mamatch,
  752. alternation = lmnt.alternation,
  753. altLocArr = lmnt.locator[alternation].toString().split(",");
  754. lmnt.locator[alternation] = undefined;
  755. lmnt.alternation = undefined;
  756. for (var alndx = 0; alndx < altLocArr.length; alndx++) {
  757. mamatch = $.inArray(altLocArr[alndx], altIndexArr) != -1;
  758. if (mamatch) { //rebuild the locator with valid entries
  759. if (lmnt.locator[alternation] != undefined) {
  760. lmnt.locator[alternation] += ",";
  761. lmnt.locator[alternation] += altLocArr[alndx];
  762. } else
  763. lmnt.locator[alternation] = parseInt(altLocArr[alndx]);
  764. lmnt.alternation = alternation;
  765. }
  766. }
  767. if (lmnt.locator[alternation] != undefined) return lmnt;
  768. }
  769. });
  770. }
  771. matches = currentMatches.concat(malternateMatches);
  772. testPos = pos;
  773. insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate
  774. } else {
  775. if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further
  776. match = handleMatch(alternateToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);
  777. } else match = false;
  778. }
  779. if (match) return true;
  780. } else if (match.isQuantifier && quantifierRecurse !== true) {
  781. var qt = match;
  782. for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0;
  783. (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {
  784. var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
  785. match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true);
  786. if (match) {
  787. //get latest match
  788. var latestMatch = matches[matches.length - 1]["match"];
  789. latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);
  790. var isFirstMatch = $.inArray(latestMatch, tokenGroup.matches) == 0;
  791. if (isFirstMatch) { //search for next possible match
  792. if (qndx > (qt.quantifier.min - 1)) {
  793. insertStop = true;
  794. testPos = pos; //match the position after the group
  795. break; //stop quantifierloop
  796. } else return true;
  797. } else {
  798. return true;
  799. }
  800. }
  801. }
  802. } else {
  803. match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
  804. if (match)
  805. return true;
  806. }
  807. } else testPos++;
  808. }
  809. for (var tndx = (ndxInitializer.length > 0 ? ndxInitializer.shift() : 0) ; tndx < maskToken.matches.length; tndx++) {
  810. if (maskToken.matches[tndx]["isQuantifier"] !== true) {
  811. var match = handleMatch(maskToken.matches[tndx], [tndx].concat(loopNdx), quantifierRecurse);
  812. if (match && testPos == pos) {
  813. return match;
  814. } else if (testPos > pos) {
  815. break;
  816. }
  817. }
  818. }
  819. }
  820. if (cacheable === true && getMaskSet()['tests'][pos]) {
  821. return getMaskSet()['tests'][pos];
  822. }
  823. if (ndxIntlzr == undefined) {
  824. var previousPos = pos - 1,
  825. test;
  826. while ((test = getMaskSet()['validPositions'][previousPos]) == undefined && previousPos > -1) {
  827. if (getMaskSet()['tests'][previousPos] && (test = getMaskSet()['tests'][previousPos][0]) != undefined)
  828. break;
  829. previousPos--;
  830. }
  831. if (test != undefined && previousPos > -1) {
  832. testPos = previousPos;
  833. ndxInitializer = test["locator"].slice();
  834. }
  835. }
  836. for (var mtndx = ndxInitializer.shift() ; mtndx < maskTokens.length; mtndx++) {
  837. var match = ResolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  838. if ((match && testPos == pos) || testPos > pos) {
  839. break;
  840. }
  841. }
  842. if (matches.length == 0 || insertStop)
  843. matches.push({
  844. "match": {
  845. fn: null,
  846. cardinality: 0,
  847. optionality: true,
  848. casing: null,
  849. def: ""
  850. },
  851. "locator": []
  852. });
  853. getMaskSet()['tests'][pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  854. //console.log(pos + " - " + JSON.stringify(matches));
  855. return getMaskSet()['tests'][pos];
  856. }
  857. function getBufferTemplate() {
  858. if (getMaskSet()['_buffer'] == undefined) {
  859. //generate template
  860. getMaskSet()["_buffer"] = getMaskTemplate(false, 1);
  861. }
  862. return getMaskSet()['_buffer'];
  863. }
  864. function getBuffer() {
  865. if (getMaskSet()['buffer'] == undefined) {
  866. getMaskSet()['buffer'] = getMaskTemplate(true, getLastValidPosition(), true);
  867. }
  868. return getMaskSet()['buffer'];
  869. }
  870. function refreshFromBuffer(start, end, buffer) {
  871. buffer = buffer || getBuffer().slice(); //pass or work on clone
  872. if (start === true) {
  873. resetMaskSet();
  874. start = 0;
  875. end = buffer.length;
  876. } else {
  877. for (var i = start; i < end; i++) {
  878. delete getMaskSet()["validPositions"][i];
  879. delete getMaskSet()["tests"][i];
  880. }
  881. }
  882. for (var i = start; i < end; i++) {
  883. if (buffer[i] != opts.skipOptionalPartCharacter) {
  884. isValid(i, buffer[i], true, true);
  885. }
  886. }
  887. }
  888. function casing(elem, test) {
  889. switch (test.casing) {
  890. case "upper":
  891. elem = elem.toUpperCase();
  892. break;
  893. case "lower":
  894. elem = elem.toLowerCase();
  895. break;
  896. }
  897. return elem;
  898. }
  899. function checkAlternationMatch(altArr1, altArr2) {
  900. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  901. isMatch = false;
  902. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  903. if ($.inArray(altArr1[alndx], altArrC) != -1) {
  904. isMatch = true;
  905. break;
  906. }
  907. }
  908. return isMatch;
  909. }
  910. function isValid(pos, c, strict, fromSetValid) { //strict true ~ no correction or autofill
  911. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  912. function _isValid(position, c, strict, fromSetValid) {
  913. var rslt = false;
  914. //console.log(JSON.stringify(getTests(position)));
  915. $.each(getTests(position), function (ndx, tst) {
  916. var test = tst["match"];
  917. var loopend = c ? 1 : 0,
  918. chrs = '',
  919. buffer = getBuffer();
  920. for (var i = test.cardinality; i > loopend; i--) {
  921. chrs += getBufferElement(position - (i - 1));
  922. }
  923. if (c) {
  924. chrs += c;
  925. }
  926. //return is false or a json object => { pos: ??, c: ??} or true
  927. rslt = test.fn != null ?
  928. test.fn.test(chrs, getMaskSet(), position, strict, opts) : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask
  929. {
  930. c: test["def"],
  931. pos: position
  932. } : false;
  933. if (rslt !== false) {
  934. var elem = rslt.c != undefined ? rslt.c : c;
  935. elem = (elem == opts.skipOptionalPartCharacter && test["fn"] === null) ? test["def"] : elem;
  936. var validatedPos = position,
  937. possibleModifiedBuffer = getBuffer();
  938. if (rslt["remove"] != undefined) { //remove position(s)
  939. if (!$.isArray(rslt["remove"])) rslt["remove"] = [rslt["remove"]];
  940. $.each(rslt["remove"].sort(function (a, b) {
  941. return b - a;
  942. }), function (ndx, lmnt) {
  943. stripValidPositions(lmnt, lmnt + 1, true);
  944. });
  945. }
  946. if (rslt["insert"] != undefined) { //insert position(s)
  947. if (!$.isArray(rslt["insert"])) rslt["insert"] = [rslt["insert"]];
  948. $.each(rslt["insert"].sort(function (a, b) {
  949. return a - b;
  950. }), function (ndx, lmnt) {
  951. isValid(lmnt["pos"], lmnt["c"], true);
  952. });
  953. }
  954. if (rslt["refreshFromBuffer"]) {
  955. var refresh = rslt["refreshFromBuffer"];
  956. strict = true;
  957. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], possibleModifiedBuffer);
  958. if (rslt.pos == undefined && rslt.c == undefined) {
  959. rslt.pos = getLastValidPosition();
  960. return false; //breakout if refreshFromBuffer && nothing to insert
  961. }
  962. validatedPos = rslt.pos != undefined ? rslt.pos : position;
  963. if (validatedPos != position) {
  964. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  965. return false;
  966. }
  967. } else if (rslt !== true && rslt.pos != undefined && rslt["pos"] != position) { //their is a position offset
  968. validatedPos = rslt["pos"];
  969. refreshFromBuffer(position, validatedPos);
  970. if (validatedPos != position) {
  971. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  972. return false;
  973. }
  974. }
  975. if (rslt != true && rslt.pos == undefined && rslt.c == undefined) {
  976. return false; //breakout if nothing to insert
  977. }
  978. if (ndx > 0) {
  979. resetMaskSet(true);
  980. }
  981. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  982. "input": casing(elem, test)
  983. }), fromSetValid))
  984. rslt = false;
  985. return false; //break from $.each
  986. }
  987. });
  988. return rslt;
  989. }
  990. function alternate(pos, c, strict, fromSetValid) {
  991. var validPsClone = $.extend(true, {}, getMaskSet()["validPositions"]),
  992. lastAlt,
  993. alternation,
  994. isValidRslt,
  995. altPos;
  996. //find last modified alternation
  997. for (var lAlt = getLastValidPosition() ; lAlt >= 0; lAlt--) {
  998. altPos = getMaskSet()["validPositions"][lAlt];
  999. if (altPos && altPos.alternation != undefined) {
  1000. lastAlt = lAlt;
  1001. alternation = getMaskSet()["validPositions"][lastAlt].alternation;
  1002. if (getTestTemplate(lastAlt).locator[altPos.alternation] != altPos.locator[altPos.alternation]) {
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. if (alternation != undefined) {
  1008. //find first decision making position
  1009. lastAlt = parseInt(lastAlt);
  1010. for (var decisionPos in getMaskSet()["validPositions"]) {
  1011. decisionPos = parseInt(decisionPos);
  1012. altPos = getMaskSet()["validPositions"][decisionPos];
  1013. if (decisionPos >= lastAlt && altPos.alternation != undefined) {
  1014. var altNdxs = getMaskSet()["validPositions"][lastAlt].locator[alternation].toString().split(','),
  1015. decisionTaker = altPos.locator[alternation] || altNdxs[0]; //no match in the alternations (length mismatch)
  1016. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1017. decisionTaker = decisionTaker.split(',')[0];
  1018. }
  1019. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1020. if (decisionTaker < altNdxs[mndx]) {
  1021. var possibilityPos, possibilities;
  1022. for (var dp = decisionPos; dp >= 0; dp--) {
  1023. possibilityPos = getMaskSet()["validPositions"][dp];
  1024. if (possibilityPos != undefined) {
  1025. possibilities = possibilityPos.locator[alternation]; //store to reset
  1026. //possibilityPos.alternation = undefined;
  1027. possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]);
  1028. break;
  1029. }
  1030. }
  1031. if (decisionTaker != possibilityPos.locator[alternation]) {
  1032. var validInputs = [],
  1033. staticInputsBeforePos = 0;
  1034. for (var i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1035. var validPos = getMaskSet()["validPositions"][i];
  1036. if (validPos) {
  1037. if (validPos.match.fn != null) {
  1038. validInputs.push(validPos.input);
  1039. } else if (i < pos) staticInputsBeforePos++;
  1040. }
  1041. delete getMaskSet()["validPositions"][i];
  1042. delete getMaskSet()["tests"][i];
  1043. }
  1044. resetMaskSet(true); //clear getbuffer
  1045. opts.keepStatic = !opts.keepStatic; //disable keepStatic on getMaskLength
  1046. isValidRslt = true;
  1047. while (validInputs.length > 0) {
  1048. var input = validInputs.shift();
  1049. //console.log(input);
  1050. if (input != opts.skipOptionalPartCharacter) {
  1051. if (!(isValidRslt = isValid(getLastValidPosition() + 1, input, false, true))) {
  1052. break;
  1053. }
  1054. }
  1055. }
  1056. possibilityPos.alternation = alternation;
  1057. possibilityPos.locator[alternation] = possibilities; //reset forceddecision ~ needed for proper delete
  1058. if (isValidRslt) {
  1059. var targetLvp = getLastValidPosition(pos) + 1;
  1060. var staticInputsBeforePosAlternate = 0;
  1061. for (var i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1062. var validPos = getMaskSet()["validPositions"][i];
  1063. if (validPos && validPos.match.fn == null && i < pos)
  1064. staticInputsBeforePosAlternate++;
  1065. }
  1066. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1067. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid);
  1068. }
  1069. opts.keepStatic = !opts.keepStatic; //enable keepStatic on getMaskLength
  1070. if (!isValidRslt) {
  1071. resetMaskSet();
  1072. getMaskSet()["validPositions"] = $.extend(true, {}, validPsClone);
  1073. } else
  1074. return isValidRslt;
  1075. }
  1076. }
  1077. }
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. return false;
  1083. }
  1084. //set alternator choice on previous skipped placeholder positions
  1085. function trackbackAlternations(originalPos, newPos) {
  1086. var vp = getMaskSet()["validPositions"][newPos],
  1087. targetLocator = vp.locator,
  1088. tll = targetLocator.length;
  1089. for (var ps = originalPos; ps < newPos; ps++) {
  1090. if (!isMask(ps)) {
  1091. var tests = getTests(ps),
  1092. bestMatch = tests[0],
  1093. equality = -1;
  1094. $.each(tests, function (ndx, tst) {
  1095. for (var i = 0; i < tll; i++) {
  1096. if (tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(','), targetLocator[i].toString().split(',')) && equality < i) {
  1097. equality = i;
  1098. bestMatch = tst;
  1099. }
  1100. }
  1101. });
  1102. setValidPosition(ps, $.extend({}, bestMatch, {
  1103. "input": bestMatch["match"].def
  1104. }), true)
  1105. }
  1106. }
  1107. }
  1108. //Check for a nonmask before the pos
  1109. var buffer = getBuffer();
  1110. //find previous valid
  1111. for (var pndx = pos - 1; pndx > -1; pndx--) {
  1112. if (getMaskSet()["validPositions"][pndx])
  1113. break;
  1114. }
  1115. ////fill missing nonmask and valid placeholders
  1116. pndx++;
  1117. for (; pndx < pos; pndx++) {
  1118. //console.log("missing " + pndx + " " + buffer[pndx] + " ismask " + isMask(pndx) + " plchldr " + getPlaceholder(pndx) + " nrt " + getTests(pndx).len);
  1119. if (getMaskSet()["validPositions"][pndx] == undefined && (((!isMask(pndx) || buffer[pndx] != getPlaceholder(pndx)) && getTests(pndx).length > 1) || (buffer[pndx] == opts.radixPoint || buffer[pndx] == "0" && $.inArray(opts.radixPoint, buffer) < pndx))) //special case for decimals ~ = placeholder but yet valid input
  1120. {
  1121. //console.log("inject " + pndx + " " + buffer[pndx]);
  1122. _isValid(pndx, buffer[pndx], true);
  1123. }
  1124. }
  1125. var maskPos = pos,
  1126. result = false,
  1127. positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]); //clone the currentPositions
  1128. //if (fromSetValid && maskPos >= getMaskLength()) {
  1129. // resetMaskSet(true); //masklenght can be altered on the process => reset to get the actual length
  1130. //}
  1131. if (maskPos < getMaskLength()) {
  1132. result = _isValid(maskPos, c, strict, fromSetValid);
  1133. if ((!strict || fromSetValid) && result === false) {
  1134. var currentPosValid = getMaskSet()["validPositions"][maskPos];
  1135. if (currentPosValid && currentPosValid["match"].fn == null && (currentPosValid["match"].def == c || c == opts.skipOptionalPartCharacter)) {
  1136. result = {
  1137. "caret": seekNext(maskPos)
  1138. };
  1139. } else if ((opts.insertMode || getMaskSet()["validPositions"][seekNext(maskPos)] == undefined) && !isMask(maskPos)) { //does the input match on a further position?
  1140. for (var nPos = maskPos + 1, snPos = seekNext(maskPos) ; nPos <= snPos; nPos++) {
  1141. result = _isValid(nPos, c, strict, fromSetValid);
  1142. if (result !== false) {
  1143. trackbackAlternations(maskPos, nPos);
  1144. maskPos = nPos;
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. if (result === false && opts.keepStatic && isComplete(buffer)) { //try fuzzy alternator logic
  1152. result = alternate(pos, c, strict, fromSetValid);
  1153. }
  1154. if (result === true) result = {
  1155. "pos": maskPos
  1156. };
  1157. if ($.isFunction(opts.postValidation) && result != false && !strict) {
  1158. resetMaskSet(true);
  1159. var postValidResult = opts.postValidation(getBuffer(), opts);
  1160. if (!postValidResult) {
  1161. resetMaskSet(true);
  1162. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone); //revert validation changes
  1163. return false;
  1164. }
  1165. }
  1166. return result;
  1167. }
  1168. function isMask(pos) {
  1169. var test = getTest(pos);
  1170. if (test.fn != null)
  1171. return test.fn
  1172. else if (!opts.keepStatic && getMaskSet()["validPositions"][pos] == undefined) {
  1173. var tests = getTests(pos),
  1174. staticAlternations = true;
  1175. for (var i = 0; i < tests.length; i++) {
  1176. if (tests[i].match.def != "" && ( /*tests[i].match.fn !== null || */ (tests[i].alternation == undefined || tests[i].locator[tests[i].alternation].length > 1))) {
  1177. staticAlternations = false;
  1178. break;
  1179. }
  1180. }
  1181. return staticAlternations;
  1182. }
  1183. return false;
  1184. }
  1185. function getMaskLength() {
  1186. var maskLength;
  1187. maxLength = $el.prop('maxLength');
  1188. if (maxLength == -1) maxLength = undefined; /* FF sets no defined max length to -1 */
  1189. var pos, lvp = getLastValidPosition(),
  1190. testPos = getMaskSet()["validPositions"][lvp],
  1191. ndxIntlzr = testPos != undefined ? testPos["locator"].slice() : undefined;
  1192. for (pos = lvp + 1; testPos == undefined || (testPos["match"]["fn"] != null || (testPos["match"]["fn"] == null && testPos["match"]["def"] != "")) ; pos++) {
  1193. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1194. ndxIntlzr = testPos["locator"].slice();
  1195. }
  1196. var lastTest = getTest(pos - 1);
  1197. maskLength = (lastTest.def != "") ? pos : pos - 1;
  1198. return (maxLength == undefined || maskLength < maxLength) ? maskLength : maxLength;
  1199. }
  1200. function seekNext(pos) {
  1201. var maskL = getMaskLength();
  1202. if (pos >= maskL) return maskL;
  1203. var position = pos;
  1204. while (++position < maskL && !isMask(position) && (opts.nojumps !== true || opts.nojumpsThreshold > position)) { }
  1205. return position;
  1206. }
  1207. function seekPrevious(pos) {
  1208. var position = pos;
  1209. if (position <= 0) return 0;
  1210. while (--position > 0 && !isMask(position)) { };
  1211. return position;
  1212. }
  1213. function getBufferElement(position) {
  1214. return getMaskSet()["validPositions"][position] == undefined ? getPlaceholder(position) : getMaskSet()["validPositions"][position]["input"];
  1215. }
  1216. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1217. if (event && $.isFunction(opts.onBeforeWrite)) {
  1218. var result = opts.onBeforeWrite.call(input, event, buffer, caretPos, opts);
  1219. if (result) {
  1220. if (result["refreshFromBuffer"]) {
  1221. var refresh = result["refreshFromBuffer"];
  1222. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], result["buffer"]);
  1223. resetMaskSet(true);
  1224. buffer = getBuffer();
  1225. }
  1226. caretPos = result.caret || caretPos;
  1227. }
  1228. }
  1229. input._valueSet(buffer.join(''));
  1230. if (caretPos != undefined) {
  1231. caret(input, caretPos);
  1232. }
  1233. if (triggerInputEvent === true) {
  1234. skipInputEvent = true;
  1235. $(input).trigger("input");
  1236. }
  1237. }
  1238. function getPlaceholder(pos, test) {
  1239. test = test || getTest(pos);
  1240. if (test["placeholder"] != undefined)
  1241. return test["placeholder"];
  1242. else if (test["fn"] == null) {
  1243. if (!opts.keepStatic && getMaskSet()["validPositions"][pos] == undefined) {
  1244. var tests = getTests(pos),
  1245. hasAlternations = false,
  1246. prevTest;
  1247. for (var i = 0; i < tests.length; i++) {
  1248. if (prevTest && tests[i].match.def != "" && (tests[i].match.def != prevTest.match.def && (tests[i].alternation == undefined || tests[i].alternation == prevTest.alternation))) {
  1249. hasAlternations = true;
  1250. break;
  1251. }
  1252. if (tests[i].match.optionality != true && tests[i].match.optionalQuantifier != true)
  1253. prevTest = tests[i];
  1254. }
  1255. if (hasAlternations)
  1256. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1257. }
  1258. return test["def"]
  1259. } else {
  1260. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1261. }
  1262. }
  1263. function checkVal(input, writeOut, strict, nptvl) {
  1264. function isTemplateMatch() {
  1265. var isMatch = false;
  1266. var charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join('').indexOf(charCodes);
  1267. if (charCodeNdx != -1 && !isMask(initialNdx)) {
  1268. isMatch = true;
  1269. var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx);
  1270. for (var i = 0; i < bufferTemplateArr.length; i++) {
  1271. if (bufferTemplateArr[i] != " ") {
  1272. isMatch = false;
  1273. break;
  1274. }
  1275. }
  1276. }
  1277. return isMatch;
  1278. }
  1279. var inputValue = nptvl != undefined ? nptvl.slice() : input._valueGet().split(''),
  1280. charCodes = "",
  1281. initialNdx = 0;
  1282. resetMaskSet();
  1283. getMaskSet()["p"] = seekNext(-1);
  1284. if (writeOut) input._valueSet(""); //initial clear
  1285. if (!strict) {
  1286. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(''),
  1287. matches = inputValue.join('').match(new RegExp("^" + escapeRegex(staticInput), "g"));
  1288. if (matches && matches.length > 0) {
  1289. inputValue.splice(0, matches.length * staticInput.length);
  1290. initialNdx = seekNext(initialNdx);
  1291. }
  1292. }
  1293. $.each(inputValue, function (ndx, charCode) {
  1294. var keypress = $.Event("keypress");
  1295. keypress.which = charCode.charCodeAt(0);
  1296. charCodes += charCode;
  1297. var lvp = getLastValidPosition(undefined, true),
  1298. lvTest = getMaskSet()["validPositions"][lvp],
  1299. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1300. if (!isTemplateMatch() || strict) {
  1301. var pos = strict ? ndx : (nextTest["match"].fn == null && nextTest["match"].optionality && (lvp + 1) < getMaskSet()["p"] ? lvp + 1 : getMaskSet()["p"]);
  1302. keypressEvent.call(input, keypress, true, false, strict, pos);
  1303. initialNdx = pos + 1;
  1304. charCodes = "";
  1305. } else {
  1306. keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1307. }
  1308. });
  1309. if (writeOut) {
  1310. writeBuffer(input, getBuffer(), $(input).is(":focus") ? seekNext(getLastValidPosition(0)) : undefined, $.Event("checkval"));
  1311. }
  1312. }
  1313. function escapeRegex(str) {
  1314. return $.inputmask.escapeRegex(str);
  1315. }
  1316. function unmaskedvalue($input) {
  1317. if ($input.data('_inputmask') && !$input.hasClass('hasDatepicker')) {
  1318. var umValue = [],
  1319. vps = getMaskSet()["validPositions"];
  1320. for (var pndx in vps) {
  1321. if (vps[pndx]["match"] && vps[pndx]["match"].fn != null) {
  1322. umValue.push(vps[pndx]["input"]);
  1323. }
  1324. }
  1325. var unmaskedValue = (isRTL ? umValue.reverse() : umValue).join('');
  1326. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join('');
  1327. if ($.isFunction(opts.onUnMask)) {
  1328. unmaskedValue = (opts.onUnMask.call($input, bufferValue, unmaskedValue, opts) || unmaskedValue);
  1329. }
  1330. return unmaskedValue;
  1331. } else {
  1332. return $input[0]._valueGet();
  1333. }
  1334. }
  1335. function TranslatePosition(pos) {
  1336. if (isRTL && typeof pos == 'number' && (!opts.greedy || opts.placeholder != "")) {
  1337. var bffrLght = getBuffer().length;
  1338. pos = bffrLght - pos;
  1339. }
  1340. return pos;
  1341. }
  1342. function caret(input, begin, end) {
  1343. var npt = input.jquery && input.length > 0 ? input[0] : input,
  1344. range;
  1345. if (typeof begin == 'number') {
  1346. begin = TranslatePosition(begin);
  1347. end = TranslatePosition(end);
  1348. end = (typeof end == 'number') ? end : begin;
  1349. if (!$(npt).is(":visible")) {
  1350. return;
  1351. }
  1352. var scrollCalc = $(npt).css("font-size").replace("px", "") * end;
  1353. npt.scrollLeft = scrollCalc > npt.scrollWidth ? scrollCalc : 0;
  1354. if (!androidchrome && opts.insertMode == false && begin == end) end++; //set visualization for insert/overwrite mode
  1355. if (npt.setSelectionRange) {
  1356. npt.selectionStart = begin;
  1357. npt.selectionEnd = end;
  1358. } else if (window.getSelection) {
  1359. range = document.createRange();
  1360. if (npt.firstChild == undefined) {
  1361. var textNode = document.createTextNode("");
  1362. npt.appendChild(textNode);
  1363. }
  1364. range.setStart(npt.firstChild, begin < npt._valueGet().length ? begin : npt._valueGet().length);
  1365. range.setEnd(npt.firstChild, end < npt._valueGet().length ? end : npt._valueGet().length);
  1366. range.collapse(true);
  1367. var sel = window.getSelection();
  1368. sel.removeAllRanges();
  1369. sel.addRange(range);
  1370. //npt.focus();
  1371. } else if (npt.createTextRange) {
  1372. range = npt.createTextRange();
  1373. range.collapse(true);
  1374. range.moveEnd('character', end);
  1375. range.moveStart('character', begin);
  1376. range.select();
  1377. }
  1378. } else {
  1379. if (npt.setSelectionRange) {
  1380. begin = npt.selectionStart;
  1381. end = npt.selectionEnd;
  1382. } else if (window.getSelection) {
  1383. range = window.getSelection().getRangeAt(0);
  1384. if (range.commonAncestorContainer.parentNode == npt || range.commonAncestorContainer == npt) {
  1385. begin = range.startOffset;
  1386. end = range.endOffset;
  1387. }
  1388. } else if (document.selection && document.selection.createRange) {
  1389. range = document.selection.createRange();
  1390. begin = 0 - range.duplicate().moveStart('character', -100000);
  1391. end = begin + range.text.length;
  1392. }
  1393. return {
  1394. "begin": TranslatePosition(begin),
  1395. "end": TranslatePosition(end)
  1396. };
  1397. }
  1398. }
  1399. function determineLastRequiredPosition(returnDefinition) {
  1400. var buffer = getBuffer(),
  1401. bl = buffer.length,
  1402. pos, lvp = getLastValidPosition(),
  1403. positions = {},
  1404. lvTest = getMaskSet()["validPositions"][lvp],
  1405. ndxIntlzr = lvTest != undefined ? lvTest["locator"].slice() : undefined,
  1406. testPos;
  1407. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1408. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1409. ndxIntlzr = testPos["locator"].slice();
  1410. positions[pos] = $.extend(true, {}, testPos);
  1411. }
  1412. var lvTestAlt = lvTest && lvTest.alternation != undefined ? lvTest["locator"][lvTest.alternation] : undefined;
  1413. for (pos = bl - 1; pos > lvp; pos--) {
  1414. testPos = positions[pos];
  1415. if ((testPos.match.optionality ||
  1416. testPos.match.optionalQuantifier ||
  1417. (lvTestAlt && ((lvTestAlt != positions[pos]["locator"][lvTest.alternation] && testPos.match.fn != null) ||
  1418. (testPos.match.fn == null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.split(",")) && getTests(pos)[0].def != "")))) && buffer[pos] == getPlaceholder(pos, testPos.match)) {
  1419. bl--;
  1420. } else break;
  1421. }
  1422. return returnDefinition ? {
  1423. "l": bl,
  1424. "def": positions[bl] ? positions[bl]["match"] : undefined
  1425. } : bl;
  1426. }
  1427. function clearOptionalTail(buffer) {
  1428. var rl = determineLastRequiredPosition(),
  1429. lmib = buffer.length - 1;
  1430. for (; lmib > rl; lmib--) {
  1431. if (isMask(lmib)) break; //fixme ismask is not good enough
  1432. }
  1433. buffer.splice(rl, lmib + 1 - rl);
  1434. return buffer
  1435. }
  1436. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1437. if ($.isFunction(opts.isComplete)) return opts.isComplete.call($el, buffer, opts);
  1438. if (opts.repeat == "*") return undefined;
  1439. var complete = false,
  1440. lrp = determineLastRequiredPosition(true),
  1441. aml = seekPrevious(lrp["l"]),
  1442. lvp = getLastValidPosition();
  1443. if (lrp["def"] == undefined || lrp["def"].newBlockMarker || lrp["def"].optionality || lrp["def"].optionalQuantifier) {
  1444. complete = true;
  1445. for (var i = 0; i <= aml; i++) {
  1446. var test = getTestTemplate(i).match;
  1447. if ((test.fn != null && getMaskSet()["validPositions"][i] == undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn == null && buffer[i] != getPlaceholder(i, test))) {
  1448. complete = false;
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. return complete;
  1454. }
  1455. function isSelection(begin, end) {
  1456. return isRTL ? (begin - end) > 1 || ((begin - end) == 1 && opts.insertMode) :
  1457. (end - begin) > 1 || ((end - begin) == 1 && opts.insertMode);
  1458. }
  1459. function installEventRuler(npt) {
  1460. var events = $._data(npt).events,
  1461. inComposition = false;
  1462. $.each(events, function (eventType, eventHandlers) {
  1463. $.each(eventHandlers, function (ndx, eventHandler) {
  1464. if (eventHandler.namespace == "inputmask") {
  1465. if (eventHandler.type != "setvalue") {
  1466. var handler = eventHandler.handler;
  1467. eventHandler.handler = function (e) {
  1468. //console.log("triggered " + e.type);
  1469. if (this.disabled || (this.readOnly && !(e.type == "keydown" && (e.ctrlKey && e.keyCode == 67) || e.keyCode == $.inputmask.keyCode.TAB)))
  1470. e.preventDefault();
  1471. else {
  1472. switch (e.type) {
  1473. case "input":
  1474. if (skipInputEvent === true || inComposition === true) {
  1475. skipInputEvent = false;
  1476. return e.preventDefault();
  1477. }
  1478. break;
  1479. case "keydown":
  1480. //Safari 5.1.x - modal dialog fires keypress twice workaround
  1481. skipKeyPressEvent = false;
  1482. inComposition = false;
  1483. break;
  1484. case "keypress":
  1485. if (skipKeyPressEvent === true)
  1486. return e.preventDefault();
  1487. skipKeyPressEvent = true;
  1488. break;
  1489. case "compositionstart":
  1490. inComposition = true;
  1491. break;
  1492. case "compositionupdate":
  1493. skipInputEvent = true;
  1494. break;
  1495. case "compositionend":
  1496. inComposition = false;
  1497. break;
  1498. }
  1499. //console.log("executed " + e.type);
  1500. return handler.apply(this, arguments);
  1501. }
  1502. };
  1503. }
  1504. }
  1505. });
  1506. });
  1507. }
  1508. function patchValueProperty(npt) {
  1509. var valueGet;
  1510. var valueSet;
  1511. function PatchValhook(type) {
  1512. if ($.valHooks[type] == undefined || $.valHooks[type].inputmaskpatch != true) {
  1513. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  1514. return elem.value;
  1515. };
  1516. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  1517. elem.value = value;
  1518. return elem;
  1519. };
  1520. $.valHooks[type] = {
  1521. get: function (elem) {
  1522. var $elem = $(elem);
  1523. if ($elem.data('_inputmask')) {
  1524. if ($elem.data('_inputmask')['opts'].autoUnmask)
  1525. return $elem.inputmask('unmaskedvalue');
  1526. else {
  1527. var result = valhookGet(elem),
  1528. inputData = $elem.data('_inputmask'),
  1529. maskset = inputData['maskset'],
  1530. bufferTemplate = maskset['_buffer'];
  1531. bufferTemplate = bufferTemplate ? bufferTemplate.join('') : '';
  1532. return result != bufferTemplate ? result : '';
  1533. }
  1534. } else return valhookGet(elem);
  1535. },
  1536. set: function (elem, value) {
  1537. var $elem = $(elem),
  1538. inputData = $elem.data('_inputmask'),
  1539. result;
  1540. result = valhookSet(elem, value);
  1541. if (inputData)
  1542. $elem.triggerHandler('setvalue.inputmask');
  1543. return result;
  1544. },
  1545. inputmaskpatch: true
  1546. };
  1547. }
  1548. }
  1549. function getter() {
  1550. var $self = $(this),
  1551. inputData = $(this).data('_inputmask');
  1552. if (inputData) {
  1553. return inputData['opts'].autoUnmask ? $self.inputmask('unmaskedvalue') : (valueGet.call(this) != getBufferTemplate().join('') ? valueGet.call(this) : '');
  1554. } else return valueGet.call(this);
  1555. }
  1556. function setter(value) {
  1557. var inputData = $(this).data('_inputmask');
  1558. valueSet.call(this, value);
  1559. if (inputData)
  1560. $(this).triggerHandler('setvalue.inputmask');
  1561. }
  1562. function InstallNativeValueSetFallback(npt) {
  1563. $(npt).bind("mouseenter.inputmask", function (event) {
  1564. var $input = $(this),
  1565. input = this,
  1566. value = input._valueGet();
  1567. if (value != "" && value != getBuffer().join(''))
  1568. $input.triggerHandler('setvalue.inputmask');
  1569. });
  1570. //!! the bound handlers are executed in the order they where bound
  1571. //reorder the events - the mouseenter event is internally mapped to the mouseover event
  1572. var events = $._data(npt).events;
  1573. var handlers = events["mouseover"];
  1574. if (handlers) {
  1575. var ourHandler = handlers[handlers.length - 1];
  1576. for (var i = handlers.length - 1; i > 0; i--) {
  1577. handlers[i] = handlers[i - 1];
  1578. }
  1579. handlers[0] = ourHandler;
  1580. }
  1581. }
  1582. if (!npt._valueGet) {
  1583. var valueProperty;
  1584. if (Object.getOwnPropertyDescriptor && npt.value == undefined) { // && npt.isContentEditable) {
  1585. valueGet = function () {
  1586. return this.textContent;
  1587. }
  1588. valueSet = function (value) {
  1589. this.textContent = value;
  1590. }
  1591. Object.defineProperty(npt, "value", {
  1592. get: getter,
  1593. set: setter
  1594. });
  1595. } else if ((valueProperty = (Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(npt, "value"))) && valueProperty.configurable && false) { //experimental for chrome
  1596. npt._value = valueProperty.value;
  1597. valueGet = function () {
  1598. return this._value || "";
  1599. }
  1600. valueSet = function (value) {
  1601. this._value = value;
  1602. this.select();
  1603. this.setRangeText(value);
  1604. this.selectionStart = this.selectionEnd;
  1605. }
  1606. Object.defineProperty(npt, "value", {
  1607. get: getter,
  1608. set: setter
  1609. });
  1610. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  1611. valueGet = npt.__lookupGetter__("value");
  1612. valueSet = npt.__lookupSetter__("value");
  1613. npt.__defineGetter__("value", getter);
  1614. npt.__defineSetter__("value", setter);
  1615. } else { //jquery.val
  1616. valueGet = function () {
  1617. return npt.value;
  1618. }
  1619. valueSet = function (value) {
  1620. npt.value = value;
  1621. }
  1622. PatchValhook(npt.type);
  1623. InstallNativeValueSetFallback(npt);
  1624. }
  1625. npt._valueGet = function (overruleRTL) {
  1626. return isRTL && overruleRTL !== true ? valueGet.call(this).split('').reverse().join('') : valueGet.call(this);
  1627. };
  1628. npt._valueSet = function (value) {
  1629. valueSet.call(this, isRTL ? value.split('').reverse().join('') : value);
  1630. };
  1631. }
  1632. }
  1633. function handleRemove(input, k, pos, strict) {
  1634. function generalize() {
  1635. if (opts.keepStatic) {
  1636. resetMaskSet(true);
  1637. var validInputs = [],
  1638. lastAlt, positionsClone = $.extend(true, {}, getMaskSet()["validPositions"]);
  1639. //find last alternation
  1640. for (lastAlt = getLastValidPosition() ; lastAlt >= 0; lastAlt--) {
  1641. var validPos = getMaskSet()["validPositions"][lastAlt];
  1642. if (validPos) {
  1643. if (validPos.match.fn != null)
  1644. validInputs.push(validPos.input);
  1645. delete getMaskSet()["validPositions"][lastAlt];
  1646. if (validPos.alternation != undefined && validPos.locator[validPos.alternation] == getTestTemplate(lastAlt).locator[validPos.alternation]) {
  1647. break;
  1648. }
  1649. }
  1650. }
  1651. if (lastAlt > -1) {
  1652. while (validInputs.length > 0) {
  1653. getMaskSet()["p"] = seekNext(getLastValidPosition());
  1654. var keypress = $.Event("keypress");
  1655. keypress.which = validInputs.pop().charCodeAt(0);
  1656. keypressEvent.call(input, keypress, true, false, false, getMaskSet()["p"]);
  1657. }
  1658. } else {
  1659. //restore original positions
  1660. getMaskSet()["validPositions"] = $.extend(true, {}, positionsClone);
  1661. }
  1662. }
  1663. }
  1664. if (opts.numericInput || isRTL) {
  1665. if (k == $.inputmask.keyCode.BACKSPACE)
  1666. k = $.inputmask.keyCode.DELETE;
  1667. else if (k == $.inputmask.keyCode.DELETE)
  1668. k = $.inputmask.keyCode.BACKSPACE;
  1669. if (isRTL) {
  1670. var pend = pos.end;
  1671. pos.end = pos.begin;
  1672. pos.begin = pend;
  1673. }
  1674. }
  1675. if (k == $.inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode == false)) {
  1676. pos.begin = seekPrevious(pos.begin);
  1677. if (getMaskSet()["validPositions"][pos.begin] != undefined && getMaskSet()["validPositions"][pos.begin].input == opts.radixPoint) {
  1678. pos.begin--;
  1679. }
  1680. } else if (k == $.inputmask.keyCode.DELETE && pos.begin == pos.end) {
  1681. pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1;
  1682. if (getMaskSet()["validPositions"][pos.begin] != undefined && getMaskSet()["validPositions"][pos.begin].input == opts.radixPoint) {
  1683. pos.end++;
  1684. }
  1685. }
  1686. stripValidPositions(pos.begin, pos.end, false, strict);
  1687. if (strict !== true) {
  1688. generalize(); //revert the alternation
  1689. var lvp = getLastValidPosition(pos.begin);
  1690. if (lvp < pos.begin) {
  1691. if (lvp == -1) resetMaskSet();
  1692. getMaskSet()["p"] = seekNext(lvp);
  1693. } else {
  1694. getMaskSet()["p"] = pos.begin;
  1695. }
  1696. }
  1697. }
  1698. //postprocessing of the validpositions according to the buffer manipulations
  1699. function handleOnKeyResult(input, keyResult, caretPos) {
  1700. if (keyResult && keyResult["refreshFromBuffer"]) {
  1701. var refresh = keyResult["refreshFromBuffer"];
  1702. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], keyResult["buffer"]);
  1703. resetMaskSet(true);
  1704. if (caretPos != undefined) {
  1705. writeBuffer(input, getBuffer());
  1706. caret(input, keyResult.caret || caretPos.begin, keyResult.caret || caretPos.end);
  1707. }
  1708. }
  1709. }
  1710. function keydownEvent(e) {
  1711. var input = this,
  1712. $input = $(input),
  1713. k = e.keyCode,
  1714. pos = caret(input);
  1715. //backspace, delete, and escape get special treatment
  1716. if (k == $.inputmask.keyCode.BACKSPACE || k == $.inputmask.keyCode.DELETE || (iphone && k == 127) || (e.ctrlKey && k == 88 && !isInputEventSupported("cut"))) { //backspace/delete
  1717. e.preventDefault(); //stop default action but allow propagation
  1718. if (k == 88) undoValue = getBuffer().join('');
  1719. handleRemove(input, k, pos);
  1720. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  1721. if (input._valueGet() == getBufferTemplate().join(''))
  1722. $input.trigger('cleared');
  1723. else if (isComplete(getBuffer()) === true)
  1724. $input.trigger("complete");
  1725. if (opts.showTooltip) { //update tooltip
  1726. $input.prop("title", getMaskSet()["mask"]);
  1727. }
  1728. } else if (k == $.inputmask.keyCode.END || k == $.inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  1729. setTimeout(function () {
  1730. var caretPos = seekNext(getLastValidPosition());
  1731. if (!opts.insertMode && caretPos == getMaskLength() && !e.shiftKey) caretPos--;
  1732. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos);
  1733. }, 0);
  1734. } else if ((k == $.inputmask.keyCode.HOME && !e.shiftKey) || k == $.inputmask.keyCode.PAGE_UP) { //Home or page_up
  1735. caret(input, 0, e.shiftKey ? pos.begin : 0);
  1736. } else if (((opts.undoOnEscape && k == $.inputmask.keyCode.ESCAPE) || (k == 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  1737. checkVal(input, true, false, undoValue.split(''));
  1738. $input.click();
  1739. } else if (k == $.inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  1740. opts.insertMode = !opts.insertMode;
  1741. caret(input, !opts.insertMode && pos.begin == getMaskLength() ? pos.begin - 1 : pos.begin);
  1742. } else if (opts.insertMode == false && !e.shiftKey) {
  1743. if (k == $.inputmask.keyCode.RIGHT) {
  1744. setTimeout(function () {
  1745. var caretPos = caret(input);
  1746. caret(input, caretPos.begin);
  1747. }, 0);
  1748. } else if (k == $.inputmask.keyCode.LEFT) {
  1749. setTimeout(function () {
  1750. var caretPos = caret(input);
  1751. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  1752. }, 0);
  1753. }
  1754. }
  1755. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  1756. ignorable = $.inArray(k, opts.ignorables) != -1;
  1757. }
  1758. function keypressEvent(e, checkval, writeOut, strict, ndx) {
  1759. var input = this,
  1760. $input = $(input),
  1761. k = e.which || e.charCode || e.keyCode;
  1762. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  1763. return true;
  1764. } else {
  1765. if (k) {
  1766. //special treat the decimal separator
  1767. if (k == 46 && e.shiftKey == false && opts.radixPoint == ",") k = 44;
  1768. var pos = checkval ? {
  1769. begin: ndx,
  1770. end: ndx
  1771. } : caret(input),
  1772. forwardPosition, c = String.fromCharCode(k);
  1773. //should we clear a possible selection??
  1774. var isSlctn = isSelection(pos.begin, pos.end);
  1775. if (isSlctn) {
  1776. getMaskSet()["undoPositions"] = $.extend(true, {}, getMaskSet()["validPositions"]); //init undobuffer for recovery when not valid
  1777. handleRemove(input, $.inputmask.keyCode.DELETE, pos, true);
  1778. pos.begin = getMaskSet()["p"];
  1779. if (!opts.insertMode) { //preserve some space
  1780. opts.insertMode = !opts.insertMode;
  1781. setValidPosition(pos.begin, strict);
  1782. opts.insertMode = !opts.insertMode;
  1783. }
  1784. isSlctn = !opts.multi;
  1785. }
  1786. getMaskSet()["writeOutBuffer"] = true;
  1787. var p = isRTL && !isSlctn ? pos.end : pos.begin;
  1788. var valResult = isValid(p, c, strict);
  1789. if (valResult !== false) {
  1790. if (valResult !== true) {
  1791. p = valResult.pos != undefined ? valResult.pos : p; //set new position from isValid
  1792. c = valResult.c != undefined ? valResult.c : c; //set new char from isValid
  1793. }
  1794. resetMaskSet(true);
  1795. if (valResult.caret != undefined)
  1796. forwardPosition = valResult.caret;
  1797. else {
  1798. var vps = getMaskSet()["validPositions"];
  1799. if (!opts.keepStatic && (vps[p + 1] != undefined && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || vps[p].alternation != undefined))
  1800. forwardPosition = p + 1;
  1801. else
  1802. forwardPosition = seekNext(p);
  1803. }
  1804. getMaskSet()["p"] = forwardPosition; //needed for checkval
  1805. }
  1806. if (writeOut !== false) {
  1807. var self = this;
  1808. setTimeout(function () {
  1809. opts.onKeyValidation.call(self, valResult, opts);
  1810. }, 0);
  1811. if (getMaskSet()["writeOutBuffer"] && valResult !== false) {
  1812. var buffer = getBuffer();
  1813. writeBuffer(input, buffer, checkval ? undefined : opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  1814. if (checkval !== true) {
  1815. setTimeout(function () { //timeout needed for IE
  1816. if (isComplete(buffer) === true)
  1817. $input.trigger("complete");
  1818. }, 0);
  1819. }
  1820. } else if (isSlctn) {
  1821. getMaskSet()["buffer"] = undefined;
  1822. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1823. }
  1824. } else if (isSlctn) {
  1825. getMaskSet()["buffer"] = undefined;
  1826. getMaskSet()["validPositions"] = getMaskSet()["undoPositions"];
  1827. }
  1828. if (opts.showTooltip) { //update tooltip
  1829. $input.prop("title", getMaskSet()["mask"]);
  1830. }
  1831. if (checkval && $.isFunction(opts.onBeforeWrite)) {
  1832. var result = opts.onBeforeWrite.call(this, e, getBuffer(), forwardPosition, opts);
  1833. if (result && result["refreshFromBuffer"]) {
  1834. var refresh = result["refreshFromBuffer"];
  1835. refreshFromBuffer(refresh === true ? refresh : refresh["start"], refresh["end"], result["buffer"]);
  1836. resetMaskSet(true);
  1837. if (result.caret) {
  1838. getMaskSet()["p"] = result.caret;
  1839. }
  1840. }
  1841. }
  1842. e.preventDefault();
  1843. }
  1844. }
  1845. }
  1846. function pasteEvent(e) {
  1847. var input = this,
  1848. $input = $(input),
  1849. inputValue = input._valueGet(true),
  1850. caretPos = caret(input);
  1851. //paste event for IE8 and lower I guess ;-)
  1852. if (e.type == "propertychange" && input._valueGet().length <= getMaskLength()) {
  1853. return true;
  1854. } else if (e.type == "paste") {
  1855. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  1856. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  1857. if (valueBeforeCaret == getBufferTemplate().slice(0, caretPos.begin).join('')) valueBeforeCaret = "";
  1858. if (valueAfterCaret == getBufferTemplate().slice(caretPos.end).join('')) valueAfterCaret = "";
  1859. if (window.clipboardData && window.clipboardData.getData) { // IE
  1860. inputValue = valueBeforeCaret + window.clipboardData.getData('Text') + valueAfterCaret;
  1861. } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
  1862. inputValue = valueBeforeCaret + e.originalEvent.clipboardData.getData('text/plain') + valueAfterCaret;
  1863. }
  1864. }
  1865. var pasteValue = inputValue;
  1866. if ($.isFunction(opts.onBeforePaste)) {
  1867. pasteValue = opts.onBeforePaste.call(input, inputValue, opts);
  1868. if (pasteValue === false) {
  1869. e.preventDefault();
  1870. return false;
  1871. }
  1872. if (!pasteValue)
  1873. pasteValue = inputValue;
  1874. }
  1875. checkVal(input, false, false, isRTL ? pasteValue.split('').reverse() : pasteValue.split(''));
  1876. writeBuffer(input, getBuffer(), undefined, e, true);
  1877. $input.click();
  1878. if (isComplete(getBuffer()) === true)
  1879. $input.trigger("complete");
  1880. return false;
  1881. }
  1882. //function mobileInputEvent(e) {
  1883. // var input = this;
  1884. // //backspace in chrome32 only fires input event - detect & treat
  1885. // var caretPos = caret(input),
  1886. // currentValue = input._valueGet();
  1887. // currentValue = currentValue.replace(new RegExp("(" + escapeRegex(getBufferTemplate().join('')) + ")*"), "");
  1888. // //correct caretposition for chrome
  1889. // if (caretPos.begin > currentValue.length) {
  1890. // caret(input, currentValue.length);
  1891. // caretPos = caret(input);
  1892. // }
  1893. // if ((getBuffer().length - currentValue.length) == 1 && currentValue.charAt(caretPos.begin) != getBuffer()[caretPos.begin]
  1894. // && currentValue.charAt(caretPos.begin + 1) != getBuffer()[caretPos.begin]
  1895. // && !isMask(caretPos.begin)) {
  1896. // e.keyCode = $.inputmask.keyCode.BACKSPACE;
  1897. // keydownEvent.call(input, e);
  1898. // }
  1899. // e.preventDefault();
  1900. //}
  1901. function inputFallBackEvent(e) { //fallback when keypress & compositionevents fail
  1902. var input = this;
  1903. checkVal(input, true, false);
  1904. if (isComplete(getBuffer()) === true)
  1905. $(input).trigger("complete");
  1906. e.preventDefault();
  1907. }
  1908. function compositionStartEvent(e) {
  1909. var input = this;
  1910. undoValue = getBuffer().join('');
  1911. if (compositionData == "" || e.originalEvent.data.indexOf(compositionData) != 0) {
  1912. compositionCaretPos = caret(input);
  1913. }
  1914. }
  1915. function compositionUpdateEvent(e) {
  1916. var input = this,
  1917. caretPos = compositionCaretPos || caret(input);
  1918. if (e.originalEvent.data.indexOf(compositionData) == 0) {
  1919. resetMaskSet();
  1920. caretPos = {
  1921. begin: 0,
  1922. end: 0
  1923. };
  1924. }
  1925. var newData = e.originalEvent.data;
  1926. caret(input, caretPos.begin, caretPos.end);
  1927. for (var i = 0; i < newData.length; i++) {
  1928. var keypress = $.Event("keypress");
  1929. keypress.which = newData.charCodeAt(i);
  1930. skipKeyPressEvent = false;
  1931. ignorable = false;
  1932. keypressEvent.call(input, keypress); //needs update
  1933. }
  1934. setTimeout(function () {
  1935. var forwardPosition = getMaskSet()["p"];
  1936. writeBuffer(input, getBuffer(), opts.numericInput ? seekPrevious(forwardPosition) : forwardPosition);
  1937. }, 0);
  1938. compositionData = e.originalEvent.data;
  1939. }
  1940. function compositionEndEvent(e) {
  1941. //pickup by inputfallback
  1942. }
  1943. function mask(el) {
  1944. $el = $(el);
  1945. //store tests & original buffer in the input element - used to get the unmasked value
  1946. $el.data('_inputmask', {
  1947. 'maskset': maskset,
  1948. 'opts': opts,
  1949. 'isRTL': false
  1950. });
  1951. //show tooltip
  1952. if (opts.showTooltip) {
  1953. $el.prop("title", getMaskSet()["mask"]);
  1954. }
  1955. if (el.dir == "rtl" || opts.rightAlign)
  1956. $el.css("text-align", "right");
  1957. if (el.dir == "rtl" || opts.numericInput) {
  1958. el.dir = "ltr";
  1959. $el.removeAttr("dir");
  1960. var inputData = $el.data('_inputmask');
  1961. inputData['isRTL'] = true;
  1962. $el.data('_inputmask', inputData);
  1963. isRTL = true;
  1964. }
  1965. //unbind all events - to make sure that no other mask will interfere when re-masking
  1966. $el.unbind(".inputmask");
  1967. if (($el.is(":input") && isInputTypeSupported($el.attr("type"))) || el.isContentEditable) {
  1968. //bind events
  1969. $el.closest('form').bind("submit", function (e) { //trigger change on submit if any
  1970. if (undoValue != getBuffer().join('')) {
  1971. $el.change();
  1972. }
  1973. if (opts.clearMaskOnLostFocus && $el[0]._valueGet && $el[0]._valueGet() == getBufferTemplate().join('')) {
  1974. $el[0]._valueSet(''); //clear masktemplete on submit and still has focus
  1975. }
  1976. if (opts.removeMaskOnSubmit) {
  1977. $el.inputmask("remove");
  1978. }
  1979. }).bind('reset', function () {
  1980. setTimeout(function () {
  1981. $el.triggerHandler('setvalue.inputmask');
  1982. }, 0);
  1983. });
  1984. $el.bind("mouseenter.inputmask", function () {
  1985. var $input = $(this),
  1986. input = this;
  1987. if (!$input.is(":focus") && opts.showMaskOnHover) {
  1988. if (input._valueGet() != getBuffer().join('')) {
  1989. writeBuffer(input, getBuffer());
  1990. }
  1991. }
  1992. }).bind("blur.inputmask", function (e) {
  1993. var $input = $(this),
  1994. input = this;
  1995. if ($input.data('_inputmask')) {
  1996. var nptValue = input._valueGet(),
  1997. buffer = getBuffer().slice();
  1998. firstClick = true;
  1999. if (undoValue != buffer.join('')) {
  2000. setTimeout(function () { //change event should be triggered after the other buffer manipulations on blur
  2001. $input.change();
  2002. undoValue = buffer.join('');
  2003. }, 0);
  2004. }
  2005. if (nptValue != '') {
  2006. if (opts.clearMaskOnLostFocus) {
  2007. if (nptValue == getBufferTemplate().join(''))
  2008. buffer = [];
  2009. else { //clearout optional tail of the mask
  2010. clearOptionalTail(buffer);
  2011. }
  2012. }
  2013. if (isComplete(buffer) === false) {
  2014. $input.trigger("incomplete");
  2015. if (opts.clearIncomplete) {
  2016. resetMaskSet();
  2017. if (opts.clearMaskOnLostFocus)
  2018. buffer = [];
  2019. else {
  2020. buffer = getBufferTemplate().slice();
  2021. }
  2022. }
  2023. }
  2024. writeBuffer(input, buffer, undefined, e);
  2025. }
  2026. }
  2027. }).bind("focus.inputmask", function (e) {
  2028. var $input = $(this),
  2029. input = this,
  2030. nptValue = input._valueGet();
  2031. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue == ''))) {
  2032. if (input._valueGet() != getBuffer().join('')) {
  2033. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2034. }
  2035. } else {
  2036. caret(input, seekNext(getLastValidPosition()));
  2037. }
  2038. undoValue = getBuffer().join('');
  2039. }).bind("mouseleave.inputmask", function () {
  2040. var $input = $(this),
  2041. input = this;
  2042. if (opts.clearMaskOnLostFocus) {
  2043. var buffer = getBuffer().slice(),
  2044. nptValue = input._valueGet();
  2045. if (!$input.is(":focus") && nptValue != $input.attr("placeholder") && nptValue != '') {
  2046. if (nptValue == getBufferTemplate().join(''))
  2047. buffer = [];
  2048. else { //clearout optional tail of the mask
  2049. clearOptionalTail(buffer);
  2050. }
  2051. writeBuffer(input, buffer);
  2052. }
  2053. }
  2054. }).bind("click.inputmask", function () {
  2055. var $input = $(this),
  2056. input = this;
  2057. if ($input.is(":focus")) {
  2058. var selectedCaret = caret(input);
  2059. if (selectedCaret.begin == selectedCaret.end) {
  2060. if (opts.radixFocus && opts.radixPoint != "" && $.inArray(opts.radixPoint, getBuffer()) != -1 && (firstClick || getBuffer().join('') == getBufferTemplate().join(''))) {
  2061. caret(input, $.inArray(opts.radixPoint, getBuffer()));
  2062. firstClick = false;
  2063. } else {
  2064. var clickPosition = TranslatePosition(selectedCaret.begin),
  2065. lastPosition = seekNext(getLastValidPosition(clickPosition));
  2066. if (clickPosition < lastPosition) {
  2067. caret(input, isMask(clickPosition) ? clickPosition : seekNext(clickPosition));
  2068. } else {
  2069. caret(input, lastPosition);
  2070. }
  2071. }
  2072. }
  2073. }
  2074. }).bind('dblclick.inputmask', function () {
  2075. var input = this;
  2076. setTimeout(function () {
  2077. caret(input, 0, seekNext(getLastValidPosition()));
  2078. }, 0);
  2079. }).bind(PasteEventType + ".inputmask dragdrop.inputmask drop.inputmask", pasteEvent).bind('cut.inputmask', function (e) {
  2080. skipInputEvent = true; //stop inputFallback
  2081. var input = this,
  2082. $input = $(input),
  2083. pos = caret(input);
  2084. handleRemove(input, $.inputmask.keyCode.DELETE, pos);
  2085. writeBuffer(input, getBuffer(), getMaskSet()["p"], e, undoValue != getBuffer().join(''));
  2086. if (input._valueGet() == getBufferTemplate().join(''))
  2087. $input.trigger('cleared');
  2088. if (opts.showTooltip) { //update tooltip
  2089. $input.prop("title", getMaskSet()["mask"]);
  2090. }
  2091. }).bind('complete.inputmask', opts.oncomplete).bind('incomplete.inputmask', opts.onincomplete).bind('cleared.inputmask', opts.oncleared);
  2092. $el.bind("keydown.inputmask", keydownEvent).bind("keypress.inputmask", keypressEvent);
  2093. if (!androidfirefox) {
  2094. $el.bind("compositionstart.inputmask", compositionStartEvent).bind("compositionupdate.inputmask", compositionUpdateEvent).bind("compositionend.inputmask", compositionEndEvent);
  2095. }
  2096. if (PasteEventType === "paste") {
  2097. $el.bind("input.inputmask", inputFallBackEvent);
  2098. }
  2099. //if (android || androidfirefox || androidchrome || kindle) {
  2100. // $el.unbind("input.inputmask");
  2101. // $el.bind("input.inputmask", mobileInputEvent);
  2102. //}
  2103. }
  2104. $el.bind('setvalue.inputmask', function () {
  2105. var input = this,
  2106. value = input._valueGet();
  2107. input._valueSet($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(input, value, opts) || value) : value);
  2108. checkVal(input, true, false);
  2109. undoValue = getBuffer().join('');
  2110. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input._valueGet() == getBufferTemplate().join(''))
  2111. input._valueSet('');
  2112. });
  2113. patchValueProperty(el);
  2114. //apply mask
  2115. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call(el, el._valueGet(), opts) || el._valueGet()) : el._valueGet();
  2116. checkVal(el, true, false, initialValue.split(''));
  2117. var buffer = getBuffer().slice();
  2118. undoValue = buffer.join('');
  2119. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2120. var activeElement;
  2121. try {
  2122. activeElement = document.activeElement;
  2123. } catch (e) { }
  2124. if (isComplete(buffer) === false) {
  2125. if (opts.clearIncomplete)
  2126. resetMaskSet();
  2127. }
  2128. if (opts.clearMaskOnLostFocus) {
  2129. if (buffer.join('') == getBufferTemplate().join('')) {
  2130. buffer = [];
  2131. } else {
  2132. clearOptionalTail(buffer);
  2133. }
  2134. }
  2135. writeBuffer(el, buffer);
  2136. if (activeElement === el) { //position the caret when in focus
  2137. caret(el, seekNext(getLastValidPosition()));
  2138. }
  2139. installEventRuler(el);
  2140. }
  2141. //action object
  2142. if (actionObj != undefined) {
  2143. switch (actionObj["action"]) {
  2144. case "isComplete":
  2145. $el = $(actionObj["el"]);
  2146. maskset = $el.data('_inputmask')['maskset'];
  2147. opts = $el.data('_inputmask')['opts'];
  2148. return isComplete(actionObj["buffer"]);
  2149. case "unmaskedvalue":
  2150. $el = actionObj["$input"];
  2151. maskset = $el.data('_inputmask')['maskset'];
  2152. opts = $el.data('_inputmask')['opts'];
  2153. isRTL = actionObj["$input"].data('_inputmask')['isRTL'];
  2154. return unmaskedvalue(actionObj["$input"]);
  2155. case "mask":
  2156. undoValue = getBuffer().join('');
  2157. mask(actionObj["el"]);
  2158. break;
  2159. case "format":
  2160. $el = $({});
  2161. $el.data('_inputmask', {
  2162. 'maskset': maskset,
  2163. 'opts': opts,
  2164. 'isRTL': opts.numericInput
  2165. });
  2166. if (opts.numericInput) {
  2167. isRTL = true;
  2168. }
  2169. var valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask.call($el, actionObj["value"], opts) || actionObj["value"]) : actionObj["value"]).split('');
  2170. checkVal($el, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2171. $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite.call(this, undefined, getBuffer(), 0, opts);
  2172. if (actionObj["metadata"]) {
  2173. return {
  2174. value: isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join(''),
  2175. metadata: $el.inputmask("getmetadata")
  2176. }
  2177. }
  2178. return isRTL ? getBuffer().slice().reverse().join('') : getBuffer().join('');
  2179. case "isValid":
  2180. $el = $({});
  2181. $el.data('_inputmask', {
  2182. 'maskset': maskset,
  2183. 'opts': opts,
  2184. 'isRTL': opts.numericInput
  2185. });
  2186. if (opts.numericInput) {
  2187. isRTL = true;
  2188. }
  2189. var valueBuffer = actionObj["value"].split('');
  2190. checkVal($el, false, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2191. var buffer = getBuffer();
  2192. var rl = determineLastRequiredPosition(),
  2193. lmib = buffer.length - 1;
  2194. for (; lmib > rl; lmib--) {
  2195. if (isMask(lmib)) break;
  2196. }
  2197. buffer.splice(rl, lmib + 1 - rl);
  2198. return isComplete(buffer) && actionObj["value"] == buffer.join('');
  2199. case "getemptymask":
  2200. $el = $(actionObj["el"]);
  2201. maskset = $el.data('_inputmask')['maskset'];
  2202. opts = $el.data('_inputmask')['opts'];
  2203. return getBufferTemplate();
  2204. case "remove":
  2205. var el = actionObj["el"];
  2206. $el = $(el);
  2207. maskset = $el.data('_inputmask')['maskset'];
  2208. opts = $el.data('_inputmask')['opts'];
  2209. //writeout the unmaskedvalue
  2210. el._valueSet(unmaskedvalue($el));
  2211. //unbind all events
  2212. $el.unbind(".inputmask");
  2213. //clear data
  2214. $el.removeData('_inputmask');
  2215. //restore the value property
  2216. var valueProperty;
  2217. if (Object.getOwnPropertyDescriptor)
  2218. valueProperty = Object.getOwnPropertyDescriptor(el, "value");
  2219. if (valueProperty && valueProperty.get) {
  2220. if (el._valueGet) {
  2221. Object.defineProperty(el, "value", {
  2222. get: el._valueGet,
  2223. set: el._valueSet
  2224. });
  2225. }
  2226. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  2227. if (el._valueGet) {
  2228. el.__defineGetter__("value", el._valueGet);
  2229. el.__defineSetter__("value", el._valueSet);
  2230. }
  2231. }
  2232. try { //try catch needed for IE7 as it does not supports deleting fns
  2233. delete el._valueGet;
  2234. delete el._valueSet;
  2235. } catch (e) {
  2236. el._valueGet = undefined;
  2237. el._valueSet = undefined;
  2238. }
  2239. break;
  2240. case "getmetadata":
  2241. $el = $(actionObj["el"]);
  2242. maskset = $el.data('_inputmask')['maskset'];
  2243. opts = $el.data('_inputmask')['opts'];
  2244. if ($.isArray(maskset["metadata"])) {
  2245. //find last alternation
  2246. var alternation, lvp = getLastValidPosition();
  2247. for (var firstAlt = lvp; firstAlt >= 0; firstAlt--) {
  2248. if (getMaskSet()["validPositions"][firstAlt] && getMaskSet()["validPositions"][firstAlt].alternation != undefined) {
  2249. alternation = getMaskSet()["validPositions"][firstAlt].alternation;
  2250. break;
  2251. }
  2252. }
  2253. if (alternation != undefined) {
  2254. return maskset["metadata"][getMaskSet()["validPositions"][lvp].locator[alternation]];
  2255. } else return maskset["metadata"][0];
  2256. }
  2257. return maskset["metadata"];
  2258. }
  2259. }
  2260. }
  2261. $.inputmask = inputmask.prototype;
  2262. $.fn.inputmask = function (fn, options) {
  2263. function importAttributeOptions(npt, opts, importedOptionsContainer) {
  2264. var $npt = $(npt);
  2265. if ($npt.data("inputmask-alias")) {
  2266. resolveAlias($npt.data("inputmask-alias"), $.extend(true, {}, opts), opts);
  2267. }
  2268. for (var option in opts) {
  2269. var optionData = $npt.data("inputmask-" + option.toLowerCase());
  2270. if (optionData != undefined) {
  2271. optionData = typeof optionData == "boolean" ? optionData : optionData.toString();
  2272. if (option == "mask" && optionData.indexOf("[") == 0) {
  2273. opts[option] = optionData.replace(/[\s[\]]/g, "").split("','");
  2274. opts[option][0] = opts[option][0].replace("'", "");
  2275. opts[option][opts[option].length - 1] = opts[option][opts[option].length - 1].replace("'", "");
  2276. } else
  2277. opts[option] = optionData;
  2278. if (importedOptionsContainer)
  2279. importedOptionsContainer[option] = opts[option];
  2280. }
  2281. }
  2282. return opts;
  2283. }
  2284. var opts = $.extend(true, {}, $.inputmask.defaults, options),
  2285. maskset;
  2286. if (typeof fn === "string") {
  2287. switch (fn) {
  2288. case "mask":
  2289. resolveAlias(opts.alias, options, opts);
  2290. return this.each(function () {
  2291. importAttributeOptions(this, opts)
  2292. maskset = generateMaskSet(opts, options && options.definitions !== undefined);
  2293. if (maskset == undefined) {
  2294. return this;
  2295. }
  2296. maskScope({
  2297. "action": "mask",
  2298. "el": this
  2299. }, maskset, opts);
  2300. });
  2301. case "unmaskedvalue":
  2302. var $input = $(this);
  2303. if ($input.data("_inputmask")) {
  2304. return maskScope({
  2305. "action": "unmaskedvalue",
  2306. "$input": $input
  2307. });
  2308. } else return $input.val();
  2309. case "remove":
  2310. return this.each(function () {
  2311. var $input = $(this);
  2312. if ($input.data("_inputmask")) {
  2313. maskScope({
  2314. "action": "remove",
  2315. "el": this
  2316. });
  2317. }
  2318. });
  2319. case "getemptymask": //return the default (empty) mask value, usefull for setting the default value in validation
  2320. if (this.data("_inputmask")) {
  2321. return maskScope({
  2322. "action": "getemptymask",
  2323. "el": this
  2324. });
  2325. } else return "";
  2326. case "hasMaskedValue": //check wheter the returned value is masked or not; currently only works reliable when using jquery.val fn to retrieve the value
  2327. return this.data("_inputmask") ? !this.data("_inputmask")['opts'].autoUnmask : false;
  2328. case "isComplete":
  2329. if (this.data("_inputmask")) {
  2330. return maskScope({
  2331. "action": "isComplete",
  2332. "buffer": this[0]._valueGet().split(''),
  2333. "el": this
  2334. });
  2335. } else return true;
  2336. case "getmetadata": //return mask metadata if exists
  2337. if (this.data("_inputmask")) {
  2338. return maskScope({
  2339. "action": "getmetadata",
  2340. "el": this
  2341. });
  2342. } else return undefined;
  2343. default:
  2344. resolveAlias(opts.alias, options, opts);
  2345. //check if the fn is an alias
  2346. if (!resolveAlias(fn, options, opts)) {
  2347. //maybe fn is a mask so we try
  2348. //set mask
  2349. opts.mask = fn;
  2350. }
  2351. return this.each(function () {
  2352. importAttributeOptions(this, opts);
  2353. maskset = generateMaskSet(opts, options && options.definitions !== undefined);
  2354. if (maskset == undefined) {
  2355. return this;
  2356. }
  2357. maskScope({
  2358. "action": "mask",
  2359. "el": this
  2360. }, maskset, opts);
  2361. });
  2362. }
  2363. } else if (typeof fn == "object") {
  2364. opts = $.extend(true, {}, $.inputmask.defaults, fn);
  2365. resolveAlias(opts.alias, fn, opts); //resolve aliases
  2366. return this.each(function () {
  2367. importAttributeOptions(this, opts);
  2368. maskset = generateMaskSet(opts, fn && fn.definitions !== undefined);
  2369. if (maskset == undefined) {
  2370. return this;
  2371. }
  2372. maskScope({
  2373. "action": "mask",
  2374. "el": this
  2375. }, maskset, opts);
  2376. });
  2377. } else if (fn == undefined) {
  2378. //look for data-inputmask atribute - the attribute should only contain optipns
  2379. return this.each(function () {
  2380. var attrOptions = $(this).attr("data-inputmask");
  2381. if (attrOptions && attrOptions != "") {
  2382. try {
  2383. attrOptions = attrOptions.replace(new RegExp("'", "g"), '"');
  2384. var dataoptions = $.parseJSON("{" + attrOptions + "}");
  2385. $.extend(true, dataoptions, options);
  2386. opts = $.extend(true, {}, $.inputmask.defaults, dataoptions);
  2387. opts = importAttributeOptions(this, opts);
  2388. resolveAlias(opts.alias, dataoptions, opts);
  2389. opts.alias = undefined;
  2390. $(this).inputmask("mask", opts);
  2391. } catch (ex) { } //need a more relax parseJSON
  2392. }
  2393. if ($(this).attr("data-inputmask-mask") || $(this).attr("data-inputmask-alias")) {
  2394. opts = $.extend(true, {}, $.inputmask.defaults, {});
  2395. var dataOptions = {};
  2396. opts = importAttributeOptions(this, opts, dataOptions);
  2397. resolveAlias(opts.alias, dataOptions, opts);
  2398. opts.alias = undefined;
  2399. $(this).inputmask("mask", opts);
  2400. }
  2401. });
  2402. }
  2403. };
  2404. }
  2405. return $.fn.inputmask;
  2406. })(jQuery);