inputmask.js 103 KB

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