inputmask.js 126 KB

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