inputmask.js 104 KB

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