inputmask.js 102 KB

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