inputmask.js 101 KB

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