inputmask.js 104 KB

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