inputmask.js 105 KB

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