inputmask.js 113 KB

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