inputmask.js 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262
  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. return [determineTestTemplate(tests)];
  1189. }
  1190. }
  1191. }
  1192. return tests;
  1193. }
  1194. if (pos > -1) {
  1195. if (ndxIntlzr === undefined) { //determine index initializer
  1196. var previousPos = pos - 1,
  1197. test;
  1198. while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
  1199. previousPos--;
  1200. }
  1201. if (test !== undefined && previousPos > -1) {
  1202. ndxInitializer = mergeLocators(test);
  1203. cacheDependency = ndxInitializer.join("");
  1204. testPos = previousPos;
  1205. }
  1206. }
  1207. if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) { //cacheDependency is set on all tests, just check on the first
  1208. //console.log("cache hit " + pos + " - " + ndxIntlzr);
  1209. return filterTests(getMaskSet().tests[pos]);
  1210. }
  1211. for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
  1212. var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [mtndx]);
  1213. if ((match && testPos === pos) || testPos > pos) {
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. if (matches.length === 0 || insertStop) {
  1219. matches.push({
  1220. match: {
  1221. fn: null,
  1222. cardinality: 0,
  1223. optionality: true,
  1224. casing: null,
  1225. def: "",
  1226. placeholder: ""
  1227. },
  1228. locator: [],
  1229. cd: cacheDependency
  1230. });
  1231. }
  1232. if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) { //prioritize full tests for caching
  1233. return filterTests($.extend(true, [], matches));
  1234. }
  1235. getMaskSet().tests[pos] = $.extend(true, [], matches); //set a clone to prevent overwriting some props
  1236. // console.log(pos + " - " + JSON.stringify(matches));
  1237. return filterTests(getMaskSet().tests[pos]);
  1238. }
  1239. function getBufferTemplate() {
  1240. if (getMaskSet()._buffer === undefined) {
  1241. //generate template
  1242. getMaskSet()._buffer = getMaskTemplate(false, 1);
  1243. if (getMaskSet().buffer === undefined) {
  1244. getMaskSet().buffer = getMaskSet()._buffer.slice();
  1245. }
  1246. }
  1247. return getMaskSet()._buffer;
  1248. }
  1249. function getBuffer(noCache) {
  1250. if (getMaskSet().buffer === undefined || noCache === true) {
  1251. getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
  1252. }
  1253. return getMaskSet().buffer;
  1254. }
  1255. function refreshFromBuffer(start, end, buffer) {
  1256. var i, p;
  1257. if (start === true) {
  1258. resetMaskSet();
  1259. start = 0;
  1260. end = buffer.length;
  1261. } else {
  1262. for (i = start; i < end; i++) {
  1263. delete getMaskSet().validPositions[i];
  1264. }
  1265. }
  1266. p = start;
  1267. for (i = start; i < end; i++) {
  1268. resetMaskSet(true); //prevents clobber from the buffer
  1269. if (buffer[i] !== opts.skipOptionalPartCharacter) {
  1270. var valResult = isValid(p, buffer[i], true, true);
  1271. if (valResult !== false) {
  1272. resetMaskSet(true);
  1273. p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
  1274. }
  1275. }
  1276. }
  1277. }
  1278. function casing(elem, test, pos) {
  1279. switch (opts.casing || test.casing) {
  1280. case "upper":
  1281. elem = elem.toUpperCase();
  1282. break;
  1283. case "lower":
  1284. elem = elem.toLowerCase();
  1285. break;
  1286. case "title":
  1287. var posBefore = getMaskSet().validPositions[pos - 1];
  1288. if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
  1289. elem = elem.toUpperCase();
  1290. } else {
  1291. elem = elem.toLowerCase();
  1292. }
  1293. break;
  1294. default:
  1295. if($.isFunction(opts.casing)){
  1296. var args = arguments.push(getMaskSet().validPositions);
  1297. elem = opts.casing.apply(this, args);
  1298. }
  1299. }
  1300. return elem;
  1301. }
  1302. function checkAlternationMatch(altArr1, altArr2, na) {
  1303. var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1),
  1304. isMatch = false, naArr = na !== undefined ? na.split(",") : [],
  1305. naNdx;
  1306. //remove no alternate indexes from alternation array
  1307. for (var i = 0; i < naArr.length; i++) {
  1308. if ((naNdx = altArr1.indexOf(naArr[i])) !== -1)
  1309. altArr1.splice(naNdx, 1);
  1310. }
  1311. for (var alndx = 0; alndx < altArr1.length; alndx++) {
  1312. if ($.inArray(altArr1[alndx], altArrC) !== -1) {
  1313. isMatch = true;
  1314. break;
  1315. }
  1316. }
  1317. return isMatch;
  1318. }
  1319. function isValid(pos, c, strict, fromSetValid, fromAlternate) { //strict true ~ no correction or autofill
  1320. function isSelection(posObj) {
  1321. var selection = isRTL ? (posObj.begin - posObj.end) > 1 || ((posObj.begin - posObj.end) === 1) :
  1322. (posObj.end - posObj.begin) > 1 || ((posObj.end - posObj.begin) === 1);
  1323. return selection && posObj.begin === 0 && posObj.end === getMaskSet().maskLength ? "full" : selection;
  1324. }
  1325. strict = strict === true; //always set a value to strict to prevent possible strange behavior in the extensions
  1326. var maskPos = pos;
  1327. if (pos.begin !== undefined) { //position was a position object - used to handle a delete by typing over a selection
  1328. maskPos = isRTL && !isSelection(pos) ? pos.end : pos.begin;
  1329. }
  1330. function _isValid(position, c, strict) {
  1331. var rslt = false;
  1332. $.each(getTests(position), function (ndx, tst) {
  1333. var test = tst.match,
  1334. loopend = c ? 1 : 0,
  1335. chrs = "";
  1336. for (var i = test.cardinality; i > loopend; i--) {
  1337. chrs += getBufferElement(position - (i - 1));
  1338. }
  1339. if (c) {
  1340. chrs += c;
  1341. }
  1342. //make sure the buffer is set and correct
  1343. getBuffer(true);
  1344. //return is false or a json object => { pos: ??, c: ??} or true
  1345. rslt = test.fn != null ?
  1346. test.fn.test(chrs, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? //non mask
  1347. {
  1348. c: getPlaceholder(position, test, true) || test.def,
  1349. pos: position
  1350. } : false;
  1351. if (rslt !== false) {
  1352. var elem = rslt.c !== undefined ? rslt.c : c;
  1353. elem = (elem === opts.skipOptionalPartCharacter && test.fn === null) ?
  1354. (getPlaceholder(position, test, true) || test.def) : elem;
  1355. var validatedPos = position,
  1356. possibleModifiedBuffer = getBuffer();
  1357. if (rslt.remove !== undefined) { //remove position(s)
  1358. if (!$.isArray(rslt.remove)) rslt.remove = [rslt.remove];
  1359. $.each(rslt.remove.sort(function (a, b) {
  1360. return b - a;
  1361. }), function (ndx, lmnt) {
  1362. stripValidPositions(lmnt, lmnt + 1, true);
  1363. });
  1364. }
  1365. if (rslt.insert !== undefined) { //insert position(s)
  1366. if (!$.isArray(rslt.insert)) rslt.insert = [rslt.insert];
  1367. $.each(rslt.insert.sort(function (a, b) {
  1368. return a - b;
  1369. }), function (ndx, lmnt) {
  1370. isValid(lmnt.pos, lmnt.c, true, fromSetValid);
  1371. });
  1372. }
  1373. if (rslt.refreshFromBuffer) {
  1374. var refresh = rslt.refreshFromBuffer;
  1375. // strict = true;
  1376. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, possibleModifiedBuffer);
  1377. if (rslt.pos === undefined && rslt.c === undefined) {
  1378. rslt.pos = getLastValidPosition();
  1379. return false; //breakout if refreshFromBuffer && nothing to insert
  1380. }
  1381. validatedPos = rslt.pos !== undefined ? rslt.pos : position;
  1382. if (validatedPos !== position) {
  1383. rslt = $.extend(rslt, isValid(validatedPos, elem, true, fromSetValid)); //revalidate new position strict
  1384. return false;
  1385. }
  1386. } else if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) { //their is a position offset
  1387. validatedPos = rslt.pos;
  1388. refreshFromBuffer(position, validatedPos, getBuffer().slice());
  1389. if (validatedPos !== position) {
  1390. rslt = $.extend(rslt, isValid(validatedPos, elem, true)); //revalidate new position strict
  1391. return false;
  1392. }
  1393. }
  1394. if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
  1395. return false; //breakout if nothing to insert
  1396. }
  1397. if (ndx > 0) {
  1398. resetMaskSet(true);
  1399. }
  1400. if (!setValidPosition(validatedPos, $.extend({}, tst, {
  1401. "input": casing(elem, test, validatedPos)
  1402. }), fromSetValid, isSelection(pos))) {
  1403. rslt = false;
  1404. }
  1405. return false; //break from $.each
  1406. }
  1407. }
  1408. );
  1409. return rslt;
  1410. }
  1411. function alternate(pos, c, strict) {
  1412. var validPsClone = $.extend(true, {}, getMaskSet().validPositions),
  1413. lastAlt,
  1414. alternation,
  1415. isValidRslt = false,
  1416. altPos, prevAltPos, i, validPos, lAltPos = getLastValidPosition(), altNdxs, decisionPos;
  1417. //find last modified alternation
  1418. prevAltPos = getMaskSet().validPositions[lAltPos];
  1419. for (; lAltPos >= 0; lAltPos--) {
  1420. altPos = getMaskSet().validPositions[lAltPos];
  1421. if (altPos && altPos.alternation !== undefined) {
  1422. lastAlt = lAltPos;
  1423. alternation = getMaskSet().validPositions[lastAlt].alternation;
  1424. if (prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
  1425. break;
  1426. }
  1427. prevAltPos = altPos;
  1428. }
  1429. }
  1430. if (alternation !== undefined) {
  1431. decisionPos = parseInt(lastAlt);
  1432. var decisionTaker = prevAltPos.locator[prevAltPos.alternation || alternation] !== undefined ? prevAltPos.locator[prevAltPos.alternation || alternation] : altNdxs[0]; //no match in the alternations (length mismatch)
  1433. if (decisionTaker.length > 0) { //no decision taken ~ take first one as decider
  1434. decisionTaker = decisionTaker.split(",")[0];
  1435. }
  1436. var possibilityPos = getMaskSet().validPositions[decisionPos],
  1437. prevPos = getMaskSet().validPositions[decisionPos - 1];
  1438. $.each(getTests(decisionPos, prevPos ? prevPos.locator : undefined, decisionPos - 1), function (ndx, test) {
  1439. altNdxs = test.locator[alternation] ? test.locator[alternation].toString().split(",") : [];
  1440. for (var mndx = 0; mndx < altNdxs.length; mndx++) {
  1441. var validInputs = [],
  1442. staticInputsBeforePos = 0,
  1443. staticInputsBeforePosAlternate = 0,
  1444. verifyValidInput = false;
  1445. if (decisionTaker < altNdxs[mndx] && (test.na === undefined || ($.inArray(altNdxs[mndx], test.na.split(",")) === -1 || $.inArray(decisionTaker.toString(), altNdxs) === -1))) {
  1446. getMaskSet().validPositions[decisionPos] = $.extend(true, {}, test);
  1447. var possibilities = getMaskSet().validPositions[decisionPos].locator;
  1448. getMaskSet().validPositions[decisionPos].locator[alternation] = parseInt(altNdxs[mndx]); //set forced decision
  1449. if (test.match.fn == null) {
  1450. if (possibilityPos.input !== test.match.def) {
  1451. verifyValidInput = true; //verify that the new definition matches the input
  1452. if (possibilityPos.generatedInput !== true) {
  1453. validInputs.push(possibilityPos.input);
  1454. }
  1455. }
  1456. staticInputsBeforePosAlternate++;
  1457. getMaskSet().validPositions[decisionPos].generatedInput = !/[0-9a-bA-Z]/.test(test.match.def);
  1458. getMaskSet().validPositions[decisionPos].input = test.match.def;
  1459. } else {
  1460. getMaskSet().validPositions[decisionPos].input = possibilityPos.input;
  1461. }
  1462. for (i = decisionPos + 1; i < getLastValidPosition(undefined, true) + 1; i++) {
  1463. validPos = getMaskSet().validPositions[i];
  1464. if (validPos && validPos.generatedInput !== true && /[0-9a-bA-Z]/.test(validPos.input)) {
  1465. validInputs.push(validPos.input);
  1466. } else if (i < pos) staticInputsBeforePos++;
  1467. delete getMaskSet().validPositions[i];
  1468. }
  1469. if (verifyValidInput && validInputs[0] === test.match.def) {
  1470. validInputs.shift();
  1471. }
  1472. resetMaskSet(true); //clear getbuffer
  1473. isValidRslt = true;
  1474. while (validInputs.length > 0) {
  1475. var input = validInputs.shift();
  1476. if (input !== opts.skipOptionalPartCharacter) {
  1477. if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. if (isValidRslt) {
  1483. getMaskSet().validPositions[decisionPos].locator = possibilities; //reset forceddecision ~ needed for proper delete
  1484. var targetLvp = getLastValidPosition(pos) + 1;
  1485. for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) {
  1486. validPos = getMaskSet().validPositions[i];
  1487. if ((validPos === undefined || validPos.match.fn == null) && i < (pos + (staticInputsBeforePosAlternate - staticInputsBeforePos))) {
  1488. staticInputsBeforePosAlternate++;
  1489. }
  1490. }
  1491. pos = pos + (staticInputsBeforePosAlternate - staticInputsBeforePos);
  1492. isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
  1493. }
  1494. if (!isValidRslt) {
  1495. resetMaskSet();
  1496. getMaskSet().validPositions = $.extend(true, {}, validPsClone);
  1497. } else return false; //exit $.each
  1498. }
  1499. }
  1500. });
  1501. }
  1502. return isValidRslt;
  1503. }
  1504. //set alternator choice on previous skipped placeholder positions
  1505. function trackbackAlternations(originalPos, newPos) {
  1506. var vp = getMaskSet().validPositions[newPos];
  1507. if (vp) {
  1508. var targetLocator = vp.locator,
  1509. tll = targetLocator.length;
  1510. for (var ps = originalPos; ps < newPos; ps++) {
  1511. if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
  1512. var tests = getTests(ps).slice(),
  1513. bestMatch = determineTestTemplate(tests, true),
  1514. equality = -1;
  1515. if (tests[tests.length - 1].match.def === "") tests.pop();
  1516. $.each(tests, function (ndx, tst) { //find best matching
  1517. for (var i = 0; i < tll; i++) {
  1518. if (tst.locator[i] !== undefined && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(","), tst.na)) {
  1519. if (equality < i) {
  1520. equality = i;
  1521. bestMatch = tst;
  1522. }
  1523. } else {
  1524. //check if alternationIndex is closer then the current bestmatch
  1525. var targetAI = targetLocator[i],
  1526. bestMatchAI = bestMatch.locator[i],
  1527. tstAI = tst.locator[i];
  1528. if ((targetAI - bestMatchAI) > Math.abs(targetAI - tstAI)) {
  1529. bestMatch = tst;
  1530. }
  1531. break;
  1532. }
  1533. }
  1534. });
  1535. bestMatch = $.extend({}, bestMatch, {
  1536. "input": getPlaceholder(ps, bestMatch.match, true) || bestMatch.match.def
  1537. });
  1538. bestMatch.generatedInput = true;
  1539. setValidPosition(ps, bestMatch, true);
  1540. //revalidate the new position to update the locator value
  1541. getMaskSet().validPositions[newPos] = undefined;
  1542. _isValid(newPos, vp.input, true);
  1543. }
  1544. }
  1545. }
  1546. }
  1547. function setValidPosition(pos, validTest, fromSetValid, isSelection) {
  1548. if (isSelection || (opts.insertMode && getMaskSet().validPositions[pos] !== undefined && fromSetValid === undefined)) {
  1549. //reposition & revalidate others
  1550. var positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  1551. lvp = getLastValidPosition(undefined, true),
  1552. i;
  1553. for (i = pos; i <= lvp; i++) { //clear selection
  1554. delete getMaskSet().validPositions[i];
  1555. }
  1556. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1557. var valid = true,
  1558. j, vps = getMaskSet().validPositions, needsValidation = false,
  1559. initialLength = getMaskSet().maskLength;
  1560. for (i = (j = pos); i <= lvp; i++) {
  1561. var t = positionsClone[i];
  1562. if (t !== undefined /*&& (t.generatedInput !== true || t.match.fn === null)*/) {
  1563. var posMatch = j;
  1564. while (posMatch < getMaskSet().maskLength && ((t.match.fn === null && vps[i] && (vps[i].match.optionalQuantifier === true || vps[i].match.optionality === true)) || t.match.fn != null)) {
  1565. posMatch++;
  1566. if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.def === t.match.def) { //obvious match
  1567. getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
  1568. getMaskSet().validPositions[posMatch].input = t.input;
  1569. fillMissingNonMask(posMatch);
  1570. j = posMatch;
  1571. valid = true;
  1572. } else if (positionCanMatchDefinition(posMatch, t.match.def)) { //validated match
  1573. var result = isValid(posMatch, t.input, true, true);
  1574. valid = result !== false;
  1575. j = (result.caret || result.insert) ? getLastValidPosition() : posMatch;
  1576. needsValidation = true;
  1577. } else {
  1578. valid = t.generatedInput === true;
  1579. if (!valid && posMatch >= getMaskSet().maskLength - 1) break;
  1580. }
  1581. if (getMaskSet().maskLength < initialLength) getMaskSet().maskLength = initialLength; //a bit hacky but the masklength is corrected later on
  1582. if (valid) break;
  1583. }
  1584. }
  1585. if (!valid) break;
  1586. }
  1587. if (!valid) {
  1588. getMaskSet().validPositions = $.extend(true, {}, positionsClone);
  1589. resetMaskSet(true);
  1590. return false;
  1591. }
  1592. }
  1593. else
  1594. getMaskSet().validPositions[pos] = $.extend(true, {}, validTest);
  1595. resetMaskSet(true);
  1596. return true;
  1597. }
  1598. function fillMissingNonMask(maskPos) {
  1599. //Check for a nonmask before the pos
  1600. //find previous valid
  1601. for (var pndx = maskPos - 1; pndx > -1; pndx--) {
  1602. if (getMaskSet().validPositions[pndx]) break;
  1603. }
  1604. ////fill missing nonmask and valid placeholders
  1605. var testTemplate, testsFromPos;
  1606. for (pndx++; pndx < maskPos; pndx++) {
  1607. if (getMaskSet().validPositions[pndx] === undefined && (opts.jitMasking === false || opts.jitMasking > pndx)) {
  1608. testsFromPos = getTests(pndx, getTestTemplate(pndx - 1).locator, pndx - 1).slice();
  1609. if (testsFromPos[testsFromPos.length - 1].match.def === "") testsFromPos.pop();
  1610. testTemplate = determineTestTemplate(testsFromPos);
  1611. if (testTemplate && (testTemplate.match.def === opts.radixPointDefinitionSymbol || !isMask(pndx, true) ||
  1612. ($.inArray(opts.radixPoint, getBuffer()) < pndx && testTemplate.match.fn && testTemplate.match.fn.test(getPlaceholder(pndx), getMaskSet(), pndx, false, opts)))) {
  1613. result = _isValid(pndx, getPlaceholder(pndx, testTemplate.match, true) || (testTemplate.match.fn == null ? testTemplate.match.def : (getPlaceholder(pndx) !== "" ? getPlaceholder(pndx) : getBuffer()[pndx])), true);
  1614. if (result !== false) {
  1615. getMaskSet().validPositions[result.pos || pndx].generatedInput = true;
  1616. }
  1617. }
  1618. }
  1619. }
  1620. }
  1621. var result = true,
  1622. positionsClone = $.extend(true, {}, getMaskSet().validPositions); //clone the currentPositions
  1623. if ($.isFunction(opts.preValidation) && !strict && fromSetValid !== true) {
  1624. result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts);
  1625. }
  1626. if (result === true) {
  1627. fillMissingNonMask(maskPos);
  1628. if (isSelection(pos)) {
  1629. handleRemove(undefined, Inputmask.keyCode.DELETE, pos);
  1630. maskPos = getMaskSet().p;
  1631. }
  1632. if (maskPos < getMaskSet().maskLength && (maxLength === undefined || maskPos < maxLength)) {
  1633. result = _isValid(maskPos, c, strict);
  1634. if ((!strict || fromSetValid === true) && result === false) {
  1635. var currentPosValid = getMaskSet().validPositions[maskPos];
  1636. if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
  1637. result = {
  1638. "caret": seekNext(maskPos)
  1639. };
  1640. } else if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos, true)) { //does the input match on a further position?
  1641. for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
  1642. // if (!isMask(nPos, true)) {
  1643. // continue;
  1644. // }
  1645. result = _isValid(nPos, c, strict);
  1646. if (result !== false) {
  1647. trackbackAlternations(maskPos, result.pos !== undefined ? result.pos : nPos);
  1648. maskPos = nPos;
  1649. break;
  1650. }
  1651. }
  1652. }
  1653. }
  1654. }
  1655. if (result === false && opts.keepStatic && !strict && fromAlternate !== true) { //try fuzzy alternator logic
  1656. result = alternate(maskPos, c, strict);
  1657. }
  1658. if (result === true) {
  1659. result = {
  1660. "pos": maskPos
  1661. };
  1662. }
  1663. }
  1664. if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true) {
  1665. var postResult = opts.postValidation(getBuffer(true), result, opts);
  1666. if (postResult.refreshFromBuffer && postResult.buffer) {
  1667. var refresh = postResult.refreshFromBuffer;
  1668. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postResult.buffer);
  1669. }
  1670. result = postResult === true ? result : postResult;
  1671. }
  1672. if (result.pos === undefined) {
  1673. result.pos = maskPos;
  1674. }
  1675. if (result === false) {
  1676. resetMaskSet(true);
  1677. getMaskSet().validPositions = $.extend(true, {}, positionsClone); //revert validation changes
  1678. }
  1679. return result;
  1680. }
  1681. function isMask(pos, strict) {
  1682. var test = getTestTemplate(pos).match;
  1683. if (test.def === "") test = getTest(pos).match;
  1684. if (test.fn != null) {
  1685. return test.fn;
  1686. } else if (strict !== true && pos > -1) {
  1687. var tests = getTests(pos);
  1688. return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
  1689. }
  1690. return false;
  1691. }
  1692. function seekNext(pos, newBlock) {
  1693. var maskL = getMaskSet().maskLength;
  1694. if (pos >= maskL) return maskL;
  1695. var position = pos;
  1696. if (getTests(maskL + 1).length > 1) {
  1697. getMaskTemplate(true, maskL + 1, true);
  1698. maskL = getMaskSet().maskLength;
  1699. }
  1700. while (++position < maskL &&
  1701. ((newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position))) ||
  1702. (newBlock !== true && !isMask(position)))) {
  1703. }
  1704. return position;
  1705. }
  1706. function seekPrevious(pos, newBlock) {
  1707. var position = pos, tests;
  1708. if (position <= 0) return 0;
  1709. while (--position > 0 &&
  1710. ((newBlock === true && getTest(position).match.newBlockMarker !== true) ||
  1711. (newBlock !== true && !isMask(position) &&
  1712. (tests = getTests(position), tests.length < 2 || (tests.length === 2 && tests[1].match.def === ""))))) {
  1713. }
  1714. return position;
  1715. }
  1716. function getBufferElement(position) {
  1717. return getMaskSet().validPositions[position] === undefined ? getPlaceholder(position) : getMaskSet().validPositions[position].input;
  1718. }
  1719. function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) {
  1720. if (event && $.isFunction(opts.onBeforeWrite)) {
  1721. var result = opts.onBeforeWrite(event, buffer, caretPos, opts);
  1722. if (result) {
  1723. if (result.refreshFromBuffer) {
  1724. var refresh = result.refreshFromBuffer;
  1725. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
  1726. buffer = getBuffer(true);
  1727. }
  1728. //only alter when intented !== undefined
  1729. if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
  1730. }
  1731. }
  1732. if (input !== undefined) {
  1733. input.inputmask._valueSet(buffer.join(""));
  1734. if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
  1735. if (android && event.type === "input") {
  1736. setTimeout(function () {
  1737. caret(input, caretPos);
  1738. }, 0);
  1739. } else caret(input, caretPos);
  1740. } else renderColorMask(input, buffer, caretPos);
  1741. if (triggerInputEvent === true) {
  1742. skipInputEvent = true;
  1743. $(input).trigger("input");
  1744. }
  1745. }
  1746. }
  1747. function getPlaceholder(pos, test, returnPL) {
  1748. test = test || getTest(pos).match;
  1749. if (test.placeholder !== undefined || returnPL === true) {
  1750. return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
  1751. } else if (test.fn === null) {
  1752. if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
  1753. var tests = getTests(pos),
  1754. staticAlternations = [],
  1755. prevTest;
  1756. if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
  1757. for (var i = 0; i < tests.length; i++) {
  1758. if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true &&
  1759. (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
  1760. staticAlternations.push(tests[i]);
  1761. if (tests[i].match.fn === null) prevTest = tests[i];
  1762. if (staticAlternations.length > 1) {
  1763. if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
  1764. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1765. }
  1766. }
  1767. }
  1768. }
  1769. }
  1770. }
  1771. return test.def;
  1772. }
  1773. return opts.placeholder.charAt(pos % opts.placeholder.length);
  1774. }
  1775. function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
  1776. var inputValue = nptvl.slice(),
  1777. charCodes = "",
  1778. initialNdx = 0, result = undefined;
  1779. // console.log(nptvl);
  1780. function isTemplateMatch(ndx, charCodes) {
  1781. var charCodeNdx = getBufferTemplate().slice(ndx, seekNext(ndx)).join("").indexOf(charCodes);
  1782. return charCodeNdx !== -1 && !isMask(ndx) && getTest(ndx).match.nativeDef === charCodes.charAt(charCodes.length - 1);
  1783. }
  1784. resetMaskSet();
  1785. getMaskSet().p = seekNext(-1);
  1786. // if (writeOut) input.inputmask._valueSet(""); //initial clear
  1787. if (!strict) {
  1788. if (opts.autoUnmask !== true) {
  1789. var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""),
  1790. matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
  1791. if (matches && matches.length > 0) {
  1792. inputValue.splice(0, matches.length * staticInput.length);
  1793. initialNdx = seekNext(initialNdx);
  1794. }
  1795. } else {
  1796. initialNdx = seekNext(initialNdx);
  1797. }
  1798. }
  1799. $.each(inputValue, function (ndx, charCode) {
  1800. console.log(charCode);
  1801. if (charCode !== undefined) { //inputfallback strips some elements out of the inputarray. $.each logically presents them as undefined
  1802. var keypress = new $.Event("_checkval");
  1803. keypress.which = charCode.charCodeAt(0);
  1804. charCodes += charCode;
  1805. var lvp = getLastValidPosition(undefined, true),
  1806. lvTest = getMaskSet().validPositions[lvp],
  1807. nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : undefined, lvp);
  1808. if (!isTemplateMatch(initialNdx, charCodes) || strict || opts.autoUnmask) {
  1809. var pos = strict ? ndx : (nextTest.match.fn == null && nextTest.match.optionality && (lvp + 1) < getMaskSet().p ? lvp + 1 : getMaskSet().p);
  1810. result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, pos);
  1811. initialNdx = pos + 1;
  1812. charCodes = "";
  1813. } else {
  1814. result = EventHandlers.keypressEvent.call(input, keypress, true, false, true, lvp + 1);
  1815. }
  1816. if (!strict && $.isFunction(opts.onBeforeWrite)) {
  1817. var fp = result.forwardPosition;
  1818. result = opts.onBeforeWrite(keypress, getBuffer(), result.forwardPosition, opts);
  1819. result.forwardPosition = fp;
  1820. if (result && result.refreshFromBuffer) {
  1821. var refresh = result.refreshFromBuffer;
  1822. refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer);
  1823. resetMaskSet(true);
  1824. if (result.caret) {
  1825. getMaskSet().p = result.caret;
  1826. result.forwardPosition = result.caret;
  1827. }
  1828. }
  1829. }
  1830. }
  1831. });
  1832. if (writeOut) {
  1833. var caretPos = undefined;
  1834. if (document.activeElement === input && result) {
  1835. caretPos = opts.numericInput ? seekPrevious(result.forwardPosition) : result.forwardPosition;
  1836. }
  1837. writeBuffer(input, getBuffer(), caretPos, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
  1838. }
  1839. }
  1840. function unmaskedvalue(input) {
  1841. if (input) {
  1842. if (input.inputmask === undefined) {
  1843. return input.value;
  1844. }
  1845. if (input.inputmask && input.inputmask.refreshValue) { //forced refresh from the value form.reset
  1846. EventHandlers.setValueEvent.call(input);
  1847. }
  1848. }
  1849. var umValue = [],
  1850. vps = getMaskSet().validPositions;
  1851. for (var pndx in vps) {
  1852. if (vps[pndx].match && vps[pndx].match.fn != null) {
  1853. umValue.push(vps[pndx].input);
  1854. }
  1855. }
  1856. var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
  1857. if ($.isFunction(opts.onUnMask)) {
  1858. var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
  1859. unmaskedValue = opts.onUnMask(bufferValue, unmaskedValue, opts);
  1860. }
  1861. return unmaskedValue;
  1862. }
  1863. function caret(input, begin, end, notranslate) {
  1864. function translatePosition(pos) {
  1865. if (notranslate !== true && isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "")) {
  1866. 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)
  1867. pos = bffrLght - pos;
  1868. }
  1869. return pos;
  1870. }
  1871. var range;
  1872. if (begin !== undefined) {
  1873. if (begin.begin !== undefined) {
  1874. end = begin.end;
  1875. begin = begin.begin;
  1876. }
  1877. if (typeof begin === "number") {
  1878. begin = translatePosition(begin);
  1879. end = translatePosition(end);
  1880. end = (typeof end == "number") ? end : begin;
  1881. // if (!$(input).is(":visible")) {
  1882. // return;
  1883. // }
  1884. var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
  1885. input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
  1886. if (!mobile && opts.insertMode === false && begin === end) end++; //set visualization for insert/overwrite mode
  1887. if (input.setSelectionRange) {
  1888. input.selectionStart = begin;
  1889. input.selectionEnd = end;
  1890. } else if (window.getSelection) {
  1891. range = document.createRange();
  1892. if (input.firstChild === undefined || input.firstChild === null) {
  1893. var textNode = document.createTextNode("");
  1894. input.appendChild(textNode);
  1895. }
  1896. range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
  1897. range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
  1898. range.collapse(true);
  1899. var sel = window.getSelection();
  1900. sel.removeAllRanges();
  1901. sel.addRange(range);
  1902. //input.focus();
  1903. } else if (input.createTextRange) {
  1904. range = input.createTextRange();
  1905. range.collapse(true);
  1906. range.moveEnd("character", end);
  1907. range.moveStart("character", begin);
  1908. range.select();
  1909. }
  1910. renderColorMask(input, undefined, {begin: begin, end: end});
  1911. }
  1912. } else {
  1913. if (input.setSelectionRange) {
  1914. begin = input.selectionStart;
  1915. end = input.selectionEnd;
  1916. } else if (window.getSelection) {
  1917. range = window.getSelection().getRangeAt(0);
  1918. if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
  1919. begin = range.startOffset;
  1920. end = range.endOffset;
  1921. }
  1922. } else if (document.selection && document.selection.createRange) {
  1923. range = document.selection.createRange();
  1924. begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
  1925. end = begin + range.text.length;
  1926. }
  1927. /*eslint-disable consistent-return */
  1928. return {
  1929. "begin": translatePosition(begin),
  1930. "end": translatePosition(end)
  1931. };
  1932. /*eslint-enable consistent-return */
  1933. }
  1934. }
  1935. function determineLastRequiredPosition(returnDefinition) {
  1936. var buffer = getBuffer(),
  1937. bl = buffer.length,
  1938. pos, lvp = getLastValidPosition(),
  1939. positions = {},
  1940. lvTest = getMaskSet().validPositions[lvp],
  1941. ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined,
  1942. testPos;
  1943. for (pos = lvp + 1; pos < buffer.length; pos++) {
  1944. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  1945. ndxIntlzr = testPos.locator.slice();
  1946. positions[pos] = $.extend(true, {}, testPos);
  1947. }
  1948. var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
  1949. for (pos = bl - 1; pos > lvp; pos--) {
  1950. testPos = positions[pos];
  1951. if ((testPos.match.optionality ||
  1952. (testPos.match.optionalQuantifier && testPos.match.newBlockMarker) ||
  1953. (lvTestAlt &&
  1954. ((lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null) ||
  1955. (testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")))) &&
  1956. buffer[pos] === getPlaceholder(pos, testPos.match)) {
  1957. bl--;
  1958. } else break;
  1959. }
  1960. return returnDefinition ? {
  1961. "l": bl,
  1962. "def": positions[bl] ? positions[bl].match : undefined
  1963. } : bl;
  1964. }
  1965. function clearOptionalTail(buffer) {
  1966. var rl = determineLastRequiredPosition(),
  1967. validPos, bl = buffer.length;
  1968. var lv = getMaskSet().validPositions[getLastValidPosition()];
  1969. while (rl < bl &&
  1970. !isMask(rl, true) &&
  1971. (validPos = (lv !== undefined ? getTestTemplate(rl, lv.locator.slice(""), lv) : getTest(rl))) &&
  1972. validPos.match.optionality !== true &&
  1973. ((validPos.match.optionalQuantifier !== true && validPos.match.newBlockMarker !== true) || (rl + 1 === bl &&
  1974. (lv !== undefined ? getTestTemplate(rl + 1, lv.locator.slice(""), lv) : getTest(rl + 1)).match.def === ""))) {
  1975. rl++;
  1976. }
  1977. //exceptionally strip from the validatedPositions
  1978. while ((validPos = getMaskSet().validPositions[rl - 1]) && validPos && validPos.match.optionality && validPos.input === opts.skipOptionalPartCharacter) {
  1979. rl--;
  1980. }
  1981. buffer.splice(rl);
  1982. return buffer;
  1983. }
  1984. function isComplete(buffer) { //return true / false / undefined (repeat *)
  1985. if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
  1986. if (opts.repeat === "*") return undefined;
  1987. var complete = false,
  1988. lrp = determineLastRequiredPosition(true),
  1989. aml = seekPrevious(lrp.l);
  1990. if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
  1991. complete = true;
  1992. for (var i = 0; i <= aml; i++) {
  1993. var test = getTestTemplate(i).match;
  1994. if ((test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true) || (test.fn === null && buffer[i] !== getPlaceholder(i, test))) {
  1995. complete = false;
  1996. break;
  1997. }
  1998. }
  1999. }
  2000. return complete;
  2001. }
  2002. function handleRemove(input, k, pos, strict) {
  2003. function generalize() {
  2004. if (opts.keepStatic) {
  2005. var validInputs = [],
  2006. lastAlt = getLastValidPosition(-1, true),
  2007. positionsClone = $.extend(true, {}, getMaskSet().validPositions),
  2008. prevAltPos = getMaskSet().validPositions[lastAlt];
  2009. //find last alternation
  2010. for (; lastAlt >= 0; lastAlt--) {
  2011. var altPos = getMaskSet().validPositions[lastAlt];
  2012. if (altPos) {
  2013. if (altPos.generatedInput !== true && /[0-9a-bA-Z]/.test(altPos.input)) {
  2014. validInputs.push(altPos.input);
  2015. }
  2016. delete getMaskSet().validPositions[lastAlt];
  2017. if (altPos.alternation !== undefined && altPos.locator[altPos.alternation] !== prevAltPos.locator[altPos.alternation]) {
  2018. break;
  2019. }
  2020. prevAltPos = altPos;
  2021. }
  2022. }
  2023. if (lastAlt > -1) {
  2024. getMaskSet().p = seekNext(getLastValidPosition(-1, true));
  2025. while (validInputs.length > 0) {
  2026. var keypress = new $.Event("keypress");
  2027. keypress.which = validInputs.pop().charCodeAt(0);
  2028. EventHandlers.keypressEvent.call(input, keypress, true, false, false, getMaskSet().p);
  2029. }
  2030. } else getMaskSet().validPositions = $.extend(true, {}, positionsClone); //restore original positions
  2031. }
  2032. }
  2033. if (opts.numericInput || isRTL) {
  2034. if (k === Inputmask.keyCode.BACKSPACE) {
  2035. k = Inputmask.keyCode.DELETE;
  2036. } else if (k === Inputmask.keyCode.DELETE) {
  2037. k = Inputmask.keyCode.BACKSPACE;
  2038. }
  2039. if (isRTL) {
  2040. var pend = pos.end;
  2041. pos.end = pos.begin;
  2042. pos.begin = pend;
  2043. }
  2044. }
  2045. if (k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === false)) {
  2046. pos.begin = seekPrevious(pos.begin);
  2047. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  2048. pos.begin--;
  2049. }
  2050. } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
  2051. pos.end = isMask(pos.end, true) ? pos.end + 1 : seekNext(pos.end) + 1;
  2052. if (getMaskSet().validPositions[pos.begin] !== undefined && (getMaskSet().validPositions[pos.begin].input === opts.groupSeparator || getMaskSet().validPositions[pos.begin].input === opts.radixPoint)) {
  2053. pos.end++;
  2054. }
  2055. }
  2056. stripValidPositions(pos.begin, pos.end, false, strict);
  2057. if (strict !== true) {
  2058. generalize(); //revert the alternation
  2059. }
  2060. var lvp = getLastValidPosition(pos.begin, true);
  2061. if (lvp < pos.begin) {
  2062. //if (lvp === -1) resetMaskSet();
  2063. getMaskSet().p = seekNext(lvp);
  2064. } else if (strict !== true) {
  2065. getMaskSet().p = pos.begin;
  2066. }
  2067. }
  2068. var EventRuler = {
  2069. on: function (input, eventName, eventHandler) {
  2070. var ev = function (e) {
  2071. // console.log("triggered " + e.type);
  2072. if (this.inputmask === undefined && this.nodeName !== "FORM") { //happens when cloning an object with jquery.clone
  2073. var imOpts = $.data(this, "_inputmask_opts");
  2074. if (imOpts) (new Inputmask(imOpts)).mask(this);
  2075. else EventRuler.off(this);
  2076. } 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))))) {
  2077. e.preventDefault();
  2078. } else {
  2079. switch (e.type) {
  2080. case "input":
  2081. if (skipInputEvent === true) {
  2082. skipInputEvent = false;
  2083. return e.preventDefault();
  2084. }
  2085. break;
  2086. case "keydown":
  2087. //Safari 5.1.x - modal dialog fires keypress twice workaround
  2088. skipKeyPressEvent = false;
  2089. skipInputEvent = false;
  2090. break;
  2091. case "keypress":
  2092. if (skipKeyPressEvent === true) {
  2093. return e.preventDefault();
  2094. }
  2095. skipKeyPressEvent = true;
  2096. break;
  2097. case "click":
  2098. if (iemobile || iphone) {
  2099. var that = this, args = arguments;
  2100. setTimeout(function () {
  2101. eventHandler.apply(that, args);
  2102. }, 0);
  2103. return false;
  2104. }
  2105. break;
  2106. }
  2107. // console.log("executed " + e.type);
  2108. var returnVal = eventHandler.apply(this, arguments);
  2109. if (returnVal === false) {
  2110. e.preventDefault();
  2111. e.stopPropagation();
  2112. }
  2113. return returnVal;
  2114. }
  2115. };
  2116. //keep instance of the event
  2117. input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
  2118. input.inputmask.events[eventName].push(ev);
  2119. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  2120. if (input.form != null) $(input.form).on(eventName, ev);
  2121. } else {
  2122. $(input).on(eventName, ev);
  2123. }
  2124. },
  2125. off: function (input, event) {
  2126. if (input.inputmask && input.inputmask.events) {
  2127. var events;
  2128. if (event) {
  2129. events = [];
  2130. events[event] = input.inputmask.events[event];
  2131. } else {
  2132. events = input.inputmask.events;
  2133. }
  2134. $.each(events, function (eventName, evArr) {
  2135. while (evArr.length > 0) {
  2136. var ev = evArr.pop();
  2137. if ($.inArray(eventName, ["submit", "reset"]) !== -1) {
  2138. if (input.form != null) $(input.form).off(eventName, ev);
  2139. } else {
  2140. $(input).off(eventName, ev);
  2141. }
  2142. }
  2143. delete input.inputmask.events[eventName];
  2144. });
  2145. }
  2146. }
  2147. };
  2148. var EventHandlers = {
  2149. keydownEvent: function (e) {
  2150. function isInputEventSupported(eventName) {
  2151. var el = document.createElement("input"),
  2152. evName = "on" + eventName,
  2153. isSupported = (evName in el);
  2154. if (!isSupported) {
  2155. el.setAttribute(evName, "return;");
  2156. isSupported = typeof el[evName] == "function";
  2157. }
  2158. el = null;
  2159. return isSupported;
  2160. }
  2161. var input = this,
  2162. $input = $(input),
  2163. k = e.keyCode,
  2164. pos = caret(input);
  2165. //backspace, delete, and escape get special treatment
  2166. 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
  2167. e.preventDefault(); //stop default action but allow propagation
  2168. handleRemove(input, k, pos);
  2169. writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
  2170. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2171. $input.trigger("cleared");
  2172. } else if (isComplete(getBuffer()) === true) {
  2173. $input.trigger("complete");
  2174. }
  2175. } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { //when END or PAGE_DOWN pressed set position at lastmatch
  2176. e.preventDefault();
  2177. var caretPos = seekNext(getLastValidPosition());
  2178. if (!opts.insertMode && caretPos === getMaskSet().maskLength && !e.shiftKey) caretPos--;
  2179. caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
  2180. } else if ((k === Inputmask.keyCode.HOME && !e.shiftKey) || k === Inputmask.keyCode.PAGE_UP) { //Home or page_up
  2181. e.preventDefault();
  2182. caret(input, 0, e.shiftKey ? pos.begin : 0, true);
  2183. } else if (((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE) || (k === 90 && e.ctrlKey)) && e.altKey !== true) { //escape && undo && #762
  2184. checkVal(input, true, false, undoValue.split(""));
  2185. $input.trigger("click");
  2186. } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) { //insert
  2187. opts.insertMode = !opts.insertMode;
  2188. caret(input, !opts.insertMode && pos.begin === getMaskSet().maskLength ? pos.begin - 1 : pos.begin);
  2189. } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
  2190. if (e.shiftKey === true) {
  2191. if (getTest(pos.begin).match.fn === null) {
  2192. pos.begin = seekNext(pos.begin);
  2193. }
  2194. pos.end = seekPrevious(pos.begin, true);
  2195. pos.begin = seekPrevious(pos.end, true);
  2196. } else {
  2197. pos.begin = seekNext(pos.begin, true);
  2198. pos.end = seekNext(pos.begin, true);
  2199. if (pos.end < getMaskSet().maskLength) pos.end--;
  2200. }
  2201. if (pos.begin < getMaskSet().maskLength) {
  2202. e.preventDefault();
  2203. caret(input, pos.begin, pos.end);
  2204. }
  2205. } else if (!e.shiftKey) {
  2206. if (opts.insertMode === false) {
  2207. if (k === Inputmask.keyCode.RIGHT) {
  2208. setTimeout(function () {
  2209. var caretPos = caret(input);
  2210. caret(input, caretPos.begin);
  2211. }, 0);
  2212. } else if (k === Inputmask.keyCode.LEFT) {
  2213. setTimeout(function () {
  2214. var caretPos = caret(input);
  2215. caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1);
  2216. }, 0);
  2217. }
  2218. }
  2219. }
  2220. opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
  2221. ignorable = $.inArray(k, opts.ignorables) !== -1;
  2222. },
  2223. keypressEvent: function (e, checkval, writeOut, strict, ndx) {
  2224. var input = this,
  2225. $input = $(input),
  2226. k = e.which || e.charCode || e.keyCode;
  2227. if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
  2228. if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
  2229. undoValue = getBuffer().join("");
  2230. // e.preventDefault();
  2231. setTimeout(function () {
  2232. $input.trigger("change");
  2233. }, 0);
  2234. }
  2235. return true;
  2236. } else {
  2237. if (k) {
  2238. //special treat the decimal separator
  2239. if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
  2240. var pos = checkval ? {
  2241. begin: ndx,
  2242. end: ndx
  2243. } : caret(input),
  2244. forwardPosition, c = String.fromCharCode(k);
  2245. getMaskSet().writeOutBuffer = true;
  2246. var valResult = isValid(pos, c, strict);
  2247. if (valResult !== false) {
  2248. resetMaskSet(true);
  2249. forwardPosition = valResult.caret !== undefined ? valResult.caret : checkval ? valResult.pos + 1 : seekNext(valResult.pos);
  2250. getMaskSet().p = forwardPosition; //needed for checkval
  2251. }
  2252. if (writeOut !== false) {
  2253. setTimeout(function () {
  2254. opts.onKeyValidation.call(input, k, valResult, opts);
  2255. }, 0);
  2256. if (getMaskSet().writeOutBuffer && valResult !== false) {
  2257. var buffer = getBuffer();
  2258. writeBuffer(input, buffer, (opts.numericInput && valResult.caret === undefined) ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== true);
  2259. if (checkval !== true) {
  2260. setTimeout(function () { //timeout needed for IE
  2261. if (isComplete(buffer) === true) $input.trigger("complete");
  2262. }, 0);
  2263. }
  2264. }
  2265. }
  2266. e.preventDefault();
  2267. if (checkval) {
  2268. valResult.forwardPosition = forwardPosition;
  2269. return valResult;
  2270. }
  2271. }
  2272. }
  2273. },
  2274. pasteEvent: function (e) {
  2275. var input = this,
  2276. ev = e.originalEvent || e,
  2277. $input = $(input),
  2278. inputValue = input.inputmask._valueGet(true),
  2279. caretPos = caret(input),
  2280. tempValue;
  2281. if (isRTL) {
  2282. tempValue = caretPos.end;
  2283. caretPos.end = caretPos.begin;
  2284. caretPos.begin = tempValue;
  2285. }
  2286. var valueBeforeCaret = inputValue.substr(0, caretPos.begin),
  2287. valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
  2288. if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
  2289. if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
  2290. if (isRTL) {
  2291. tempValue = valueBeforeCaret;
  2292. valueBeforeCaret = valueAfterCaret;
  2293. valueAfterCaret = tempValue;
  2294. }
  2295. if (window.clipboardData && window.clipboardData.getData) { // IE
  2296. inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
  2297. } else if (ev.clipboardData && ev.clipboardData.getData) {
  2298. inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
  2299. } else return true; //allow native paste event as fallback ~ masking will continue by inputfallback
  2300. var pasteValue = inputValue;
  2301. if ($.isFunction(opts.onBeforePaste)) {
  2302. pasteValue = opts.onBeforePaste(inputValue, opts);
  2303. if (pasteValue === false) {
  2304. return e.preventDefault();
  2305. }
  2306. if (!pasteValue) {
  2307. pasteValue = inputValue;
  2308. }
  2309. }
  2310. checkVal(input, false, false, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split(""));
  2311. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
  2312. if (isComplete(getBuffer()) === true) {
  2313. $input.trigger("complete");
  2314. }
  2315. return e.preventDefault();
  2316. },
  2317. inputFallBackEvent: function (e) { //fallback when keypress is not triggered
  2318. var input = this,
  2319. inputValue = input.inputmask._valueGet();
  2320. if (getBuffer().join("") !== inputValue) {
  2321. var caretPos = caret(input);
  2322. //radixpoint tweak
  2323. if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
  2324. inputValue = inputValue.split("");
  2325. inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
  2326. inputValue = inputValue.join("");
  2327. }
  2328. if (inputValue.charAt(caretPos.begin - 1) === opts.radixPoint && inputValue.length > getBuffer().length) {
  2329. var keypress = new $.Event("keypress");
  2330. keypress.which = opts.radixPoint.charCodeAt(0);
  2331. EventHandlers.keypressEvent.call(input, keypress, true, true, false, caretPos.begin);
  2332. return false;
  2333. }
  2334. inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), "");
  2335. if (iemobile) { //iemobile just set the character at the end althought the caret position is correctly set
  2336. var inputChar = inputValue.replace(getBuffer().join(""), "");
  2337. if (inputChar.length === 1) {
  2338. var keypress = new $.Event("keypress");
  2339. keypress.which = inputChar.charCodeAt(0);
  2340. EventHandlers.keypressEvent.call(input, keypress, true, true, false, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1);
  2341. return false;
  2342. }
  2343. }
  2344. if (caretPos.begin > inputValue.length) {
  2345. caret(input, inputValue.length);
  2346. caretPos = caret(input);
  2347. }
  2348. //detect & treat possible backspace before static
  2349. if ((getBuffer().length - inputValue.length) === 1 && inputValue.charAt(caretPos.begin) !== getBuffer()[caretPos.begin] && inputValue.charAt(caretPos.begin + 1) !== getBuffer()[caretPos.begin] && !isMask(caretPos.begin)) {
  2350. e.keyCode = Inputmask.keyCode.BACKSPACE;
  2351. EventHandlers.keydownEvent.call(input, e);
  2352. } else {
  2353. var stickyParts = [], bufferTemplate = getMaskTemplate(true, 1).join("");
  2354. stickyParts.push(inputValue.substr(0, caretPos.begin));
  2355. stickyParts.push(inputValue.substr(caretPos.begin));
  2356. // console.log(stickyParts[0] + " , " + stickyParts[1]);
  2357. while (inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$") === null) {
  2358. bufferTemplate = bufferTemplate.slice(1);
  2359. }
  2360. // console.log("initial " + inputValue);
  2361. inputValue = inputValue.replace(bufferTemplate, "");
  2362. // console.log(inputValue);
  2363. if ($.isFunction(opts.onBeforeMask)) inputValue = opts.onBeforeMask(inputValue, opts) || inputValue;
  2364. checkVal(input, true, false, inputValue.split(""), e);
  2365. //correct caret position
  2366. var currentPos = caret(input).begin, currentValue = input.inputmask._valueGet();
  2367. var pos1 = currentValue.indexOf(stickyParts[0]);
  2368. if (pos1 === 0 && currentPos !== stickyParts[0].length) {
  2369. // console.log("set caret to " + stickyParts[0].length);
  2370. caret(input, stickyParts[0].length);
  2371. if (android) { //caret is set by android after inputevent
  2372. setTimeout(function () {
  2373. caret(input, stickyParts[0].length);
  2374. }, 0);
  2375. }
  2376. } else {
  2377. // console.log(currentValue);
  2378. while (currentValue.match(Inputmask.escapeRegex(stickyParts[1]) + "$") === null) {
  2379. stickyParts[1] = stickyParts[1].substr(1);
  2380. }
  2381. var pos2 = currentValue.indexOf(stickyParts[1]);
  2382. if (pos2 !== -1 && stickyParts[1] !== "" && currentPos > pos2 && pos2 > pos1) {
  2383. // console.log("set caret to2 " + pos2 + " - " + currentPos);
  2384. caret(input, pos2);
  2385. if (android) { //caret is set by android after inputevent
  2386. setTimeout(function () {
  2387. caret(input, pos2);
  2388. }, 0);
  2389. }
  2390. }
  2391. }
  2392. if (isComplete(getBuffer()) === true) {
  2393. $(input).trigger("complete");
  2394. }
  2395. }
  2396. e.preventDefault();
  2397. }
  2398. },
  2399. setValueEvent: function (e) {
  2400. this.inputmask.refreshValue = false;
  2401. var input = this,
  2402. value = input.inputmask._valueGet(true);
  2403. if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask(value, opts) || value;
  2404. value = value.split("");
  2405. checkVal(input, true, false, isRTL ? value.reverse() : value);
  2406. undoValue = getBuffer().join("");
  2407. if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2408. input.inputmask._valueSet("");
  2409. }
  2410. }
  2411. ,
  2412. focusEvent: function (e) {
  2413. var input = this,
  2414. nptValue = input.inputmask._valueGet();
  2415. if (opts.showMaskOnFocus && (!opts.showMaskOnHover || (opts.showMaskOnHover && nptValue === ""))) {
  2416. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2417. writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
  2418. } else if (mouseEnter === false) { //only executed on focus without mouseenter
  2419. caret(input, seekNext(getLastValidPosition()));
  2420. }
  2421. }
  2422. if (opts.positionCaretOnTab === true && mouseEnter === false) {
  2423. writeBuffer(input, getBuffer(), caret(input));
  2424. EventHandlers.clickEvent.apply(input, [e, true]);
  2425. }
  2426. undoValue = getBuffer().join("");
  2427. }
  2428. ,
  2429. mouseleaveEvent: function (e) {
  2430. var input = this;
  2431. mouseEnter = false;
  2432. if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
  2433. var buffer = getBuffer().slice(),
  2434. nptValue = input.inputmask._valueGet();
  2435. if (nptValue !== input.getAttribute("placeholder") && nptValue !== "") {
  2436. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2437. buffer = [];
  2438. } else { //clearout optional tail of the mask
  2439. clearOptionalTail(buffer);
  2440. }
  2441. writeBuffer(input, buffer);
  2442. }
  2443. }
  2444. }
  2445. ,
  2446. clickEvent: function (e, tabbed) {
  2447. function doRadixFocus(clickPos) {
  2448. if (opts.radixPoint !== "") {
  2449. var vps = getMaskSet().validPositions;
  2450. if (vps[clickPos] === undefined || (vps[clickPos].input === getPlaceholder(clickPos))) {
  2451. if (clickPos < seekNext(-1)) return true;
  2452. var radixPos = $.inArray(opts.radixPoint, getBuffer());
  2453. if (radixPos !== -1) {
  2454. for (var vp in vps) {
  2455. if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
  2456. return false;
  2457. }
  2458. }
  2459. return true;
  2460. }
  2461. }
  2462. }
  2463. return false;
  2464. }
  2465. var input = this;
  2466. setTimeout(function () { //needed for Chrome ~ initial selection clears after the clickevent
  2467. if (document.activeElement === input) {
  2468. var selectedCaret = caret(input);
  2469. if (tabbed) {
  2470. if (isRTL)
  2471. selectedCaret.end = selectedCaret.begin;
  2472. else
  2473. selectedCaret.begin = selectedCaret.end;
  2474. }
  2475. if (selectedCaret.begin === selectedCaret.end) {
  2476. switch (opts.positionCaretOnClick) {
  2477. case "none":
  2478. break;
  2479. case "radixFocus":
  2480. if (doRadixFocus(selectedCaret.begin)) {
  2481. var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
  2482. caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
  2483. break;
  2484. }
  2485. default: //lvp:
  2486. var clickPosition = selectedCaret.begin,
  2487. lvclickPosition = getLastValidPosition(clickPosition, true),
  2488. lastPosition = seekNext(lvclickPosition);
  2489. if (clickPosition < lastPosition) {
  2490. caret(input, !isMask(clickPosition) && !isMask(clickPosition - 1) ? seekNext(clickPosition) : clickPosition);
  2491. } else {
  2492. var placeholder = getPlaceholder(lastPosition);
  2493. if ((placeholder !== "" && getBuffer()[lastPosition] !== placeholder && getTest(lastPosition).match.optionalQuantifier !== true) || (!isMask(lastPosition) && getTest(lastPosition).match.def === placeholder)) {
  2494. lastPosition = seekNext(lastPosition);
  2495. }
  2496. caret(input, lastPosition);
  2497. }
  2498. break;
  2499. }
  2500. }
  2501. }
  2502. }, 0);
  2503. }
  2504. ,
  2505. dblclickEvent: function (e) {
  2506. var input = this;
  2507. setTimeout(function () {
  2508. caret(input, 0, seekNext(getLastValidPosition()));
  2509. }, 0);
  2510. },
  2511. cutEvent: function (e) {
  2512. var input = this,
  2513. $input = $(input),
  2514. pos = caret(input),
  2515. ev = e.originalEvent || e;
  2516. //correct clipboardData
  2517. var clipboardData = window.clipboardData || ev.clipboardData,
  2518. clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
  2519. clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
  2520. if (document.execCommand) document.execCommand("copy"); // copy selected content to system clipbaord
  2521. handleRemove(input, Inputmask.keyCode.DELETE, pos);
  2522. writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
  2523. if (input.inputmask._valueGet() === getBufferTemplate().join("")) {
  2524. $input.trigger("cleared");
  2525. }
  2526. },
  2527. blurEvent: function (e) {
  2528. var $input = $(this),
  2529. input = this;
  2530. if (input.inputmask) {
  2531. var nptValue = input.inputmask._valueGet(),
  2532. buffer = getBuffer().slice();
  2533. if (nptValue !== "") {
  2534. if (opts.clearMaskOnLostFocus) {
  2535. if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
  2536. buffer = [];
  2537. } else { //clearout optional tail of the mask
  2538. clearOptionalTail(buffer);
  2539. }
  2540. }
  2541. if (isComplete(buffer) === false) {
  2542. setTimeout(function () {
  2543. $input.trigger("incomplete");
  2544. }, 0);
  2545. if (opts.clearIncomplete) {
  2546. resetMaskSet();
  2547. if (opts.clearMaskOnLostFocus) {
  2548. buffer = [];
  2549. } else {
  2550. buffer = getBufferTemplate().slice();
  2551. }
  2552. }
  2553. }
  2554. writeBuffer(input, buffer, undefined, e);
  2555. }
  2556. if (undoValue !== getBuffer().join("")) {
  2557. undoValue = buffer.join("");
  2558. $input.trigger("change");
  2559. }
  2560. }
  2561. },
  2562. mouseenterEvent: function (e) {
  2563. var input = this;
  2564. mouseEnter = true;
  2565. if (document.activeElement !== input && opts.showMaskOnHover) {
  2566. if (input.inputmask._valueGet() !== getBuffer().join("")) {
  2567. writeBuffer(input, getBuffer());
  2568. }
  2569. }
  2570. }
  2571. ,
  2572. submitEvent: function (e) { //trigger change on submit if any
  2573. if (undoValue !== getBuffer().join("")) {
  2574. $el.trigger("change");
  2575. }
  2576. if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
  2577. el.inputmask._valueSet(""); //clear masktemplete on submit and still has focus
  2578. }
  2579. if (opts.removeMaskOnSubmit) {
  2580. el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
  2581. setTimeout(function () {
  2582. writeBuffer(el, getBuffer());
  2583. }, 0);
  2584. }
  2585. }
  2586. ,
  2587. resetEvent: function (e) {
  2588. el.inputmask.refreshValue = true; //indicate a forced refresh when there is a call to the value before leaving the triggering event fn
  2589. setTimeout(function () {
  2590. $el.trigger("setvalue");
  2591. }, 0);
  2592. }
  2593. };
  2594. function initializeColorMask(input) {
  2595. function findCaretPos(clientx) {
  2596. //calculate text width
  2597. var e = document.createElement('span'), caretPos;
  2598. for (var style in computedStyle) { //clone styles
  2599. if (isNaN(style) && style.indexOf("font") !== -1) {
  2600. e.style[style] = computedStyle[style];
  2601. }
  2602. }
  2603. e.style.textTransform = computedStyle.textTransform;
  2604. e.style.letterSpacing = computedStyle.letterSpacing;
  2605. e.style.position = "absolute";
  2606. e.style.height = "auto";
  2607. e.style.width = "auto";
  2608. e.style.visibility = "hidden";
  2609. e.style.whiteSpace = "nowrap";
  2610. document.body.appendChild(e);
  2611. var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
  2612. for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
  2613. e.innerHTML += inputText.charAt(caretPos) || "_";
  2614. if (e.offsetWidth >= clientx) {
  2615. var offset1 = (clientx - previousWidth);
  2616. var offset2 = e.offsetWidth - clientx;
  2617. e.innerHTML = inputText.charAt(caretPos);
  2618. offset1 -= (e.offsetWidth / 3);
  2619. caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
  2620. break;
  2621. }
  2622. previousWidth = e.offsetWidth;
  2623. }
  2624. document.body.removeChild(e);
  2625. return caretPos;
  2626. }
  2627. function position() {
  2628. colorMask.style.position = "absolute";
  2629. colorMask.style.top = offset.top + "px";
  2630. colorMask.style.left = offset.left + "px";
  2631. colorMask.style.width = parseInt(input.offsetWidth) - parseInt(computedStyle.paddingLeft) - parseInt(computedStyle.paddingRight) - parseInt(computedStyle.borderLeftWidth) - parseInt(computedStyle.borderRightWidth) + "px";
  2632. colorMask.style.height = parseInt(input.offsetHeight) - parseInt(computedStyle.paddingTop) - parseInt(computedStyle.paddingBottom) - parseInt(computedStyle.borderTopWidth) - parseInt(computedStyle.borderBottomWidth) + "px";
  2633. colorMask.style.lineHeight = colorMask.style.height;
  2634. colorMask.style.zIndex = isNaN(computedStyle.zIndex) ? -1 : computedStyle.zIndex - 1;
  2635. colorMask.style.webkitAppearance = "textfield";
  2636. colorMask.style.mozAppearance = "textfield";
  2637. colorMask.style.Appearance = "textfield";
  2638. }
  2639. var offset = $(input).position(),
  2640. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null),
  2641. parentNode = input.parentNode;
  2642. colorMask = document.createElement("div");
  2643. document.body.appendChild(colorMask); //insert at body to prevent css clash :last-child for example
  2644. for (var style in computedStyle) { //clone styles
  2645. if (computedStyle.hasOwnProperty(style))
  2646. if (isNaN(style) && style !== "cssText" && style.indexOf("webkit") == -1) {
  2647. colorMask.style[style] = computedStyle[style];
  2648. }
  2649. }
  2650. //restyle input
  2651. input.style.backgroundColor = "transparent";
  2652. input.style.color = "transparent";
  2653. input.style.webkitAppearance = "caret";
  2654. input.style.mozAppearance = "caret";
  2655. input.style.Appearance = "caret";
  2656. position();
  2657. //event passthrough
  2658. $(window).on("resize", function (e) {
  2659. offset = $(input).position();
  2660. computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
  2661. position();
  2662. });
  2663. $(input).on("click", function (e) {
  2664. caret(input, findCaretPos(e.clientX));
  2665. return EventHandlers.clickEvent.call(this, [e]);
  2666. });
  2667. $(input).on("keydown", function (e) {
  2668. if (!e.shiftKey && opts.insertMode !== false) {
  2669. setTimeout(function () {
  2670. renderColorMask(input);
  2671. }, 0);
  2672. }
  2673. });
  2674. }
  2675. function renderColorMask(input, buffer, caretPos) {
  2676. function handleStatic() {
  2677. if (!isStatic && (test.fn === null || testPos.input === undefined)) {
  2678. isStatic = true;
  2679. maskTemplate += "<span class='im-static''>"
  2680. } else if (isStatic && (test.fn !== null && testPos.input !== undefined)) {
  2681. isStatic = false;
  2682. maskTemplate += "</span>"
  2683. }
  2684. }
  2685. if (colorMask !== undefined) {
  2686. buffer = buffer || getBuffer();
  2687. if (caretPos === undefined) {
  2688. caretPos = caret(input);
  2689. } else if (caretPos.begin === undefined) {
  2690. caretPos = {begin: caretPos, end: caretPos};
  2691. }
  2692. var maskTemplate = "", isStatic = false;
  2693. if (buffer != "") {
  2694. var ndxIntlzr, pos = 0,
  2695. test, testPos, lvp = getLastValidPosition();
  2696. do {
  2697. if (pos === caretPos.begin && document.activeElement === input) {
  2698. maskTemplate += "<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'></span>";
  2699. }
  2700. if (getMaskSet().validPositions[pos]) {
  2701. testPos = getMaskSet().validPositions[pos];
  2702. test = testPos.match;
  2703. ndxIntlzr = testPos.locator.slice();
  2704. handleStatic();
  2705. maskTemplate += testPos.input;
  2706. } else {
  2707. testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
  2708. test = testPos.match;
  2709. ndxIntlzr = testPos.locator.slice();
  2710. if (opts.jitMasking === false || pos < lvp || (typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos)) {
  2711. handleStatic();
  2712. maskTemplate += getPlaceholder(pos, test);
  2713. }
  2714. }
  2715. pos++;
  2716. } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos);
  2717. }
  2718. colorMask.innerHTML = maskTemplate;
  2719. }
  2720. }
  2721. function mask(elem) {
  2722. function isElementTypeSupported(input, opts) {
  2723. function patchValueProperty(npt) {
  2724. var valueGet;
  2725. var valueSet;
  2726. function patchValhook(type) {
  2727. if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
  2728. var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function (elem) {
  2729. return elem.value;
  2730. };
  2731. var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function (elem, value) {
  2732. elem.value = value;
  2733. return elem;
  2734. };
  2735. $.valHooks[type] = {
  2736. get: function (elem) {
  2737. if (elem.inputmask) {
  2738. if (elem.inputmask.opts.autoUnmask) {
  2739. return elem.inputmask.unmaskedvalue();
  2740. } else {
  2741. var result = valhookGet(elem);
  2742. return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
  2743. }
  2744. } else return valhookGet(elem);
  2745. },
  2746. set: function (elem, value) {
  2747. var $elem = $(elem),
  2748. result;
  2749. result = valhookSet(elem, value);
  2750. if (elem.inputmask) {
  2751. $elem.trigger("setvalue");
  2752. }
  2753. return result;
  2754. },
  2755. inputmaskpatch: true
  2756. };
  2757. }
  2758. }
  2759. function getter() {
  2760. if (this.inputmask) {
  2761. return this.inputmask.opts.autoUnmask ?
  2762. this.inputmask.unmaskedvalue() :
  2763. (getLastValidPosition() !== -1 || opts.nullable !== true ?
  2764. (document.activeElement === this && opts.clearMaskOnLostFocus ?
  2765. (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") :
  2766. valueGet.call(this)) :
  2767. "");
  2768. } else return valueGet.call(this);
  2769. }
  2770. function setter(value) {
  2771. valueSet.call(this, value);
  2772. if (this.inputmask) {
  2773. $(this).trigger("setvalue");
  2774. }
  2775. }
  2776. function installNativeValueSetFallback(npt) {
  2777. EventRuler.on(npt, "mouseenter", function (event) {
  2778. var $input = $(this),
  2779. input = this,
  2780. value = input.inputmask._valueGet();
  2781. if (value !== getBuffer().join("") /*&& getLastValidPosition() > 0*/) {
  2782. $input.trigger("setvalue");
  2783. }
  2784. });
  2785. }
  2786. if (!npt.inputmask.__valueGet) {
  2787. if (opts.noValuePatching !== true) {
  2788. if (Object.getOwnPropertyDescriptor) {
  2789. if (typeof Object.getPrototypeOf !== "function") {
  2790. Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function (object) {
  2791. return object.__proto__;
  2792. } : function (object) {
  2793. return object.constructor.prototype;
  2794. };
  2795. }
  2796. var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
  2797. if (valueProperty && valueProperty.get && valueProperty.set) {
  2798. valueGet = valueProperty.get;
  2799. valueSet = valueProperty.set;
  2800. Object.defineProperty(npt, "value", {
  2801. get: getter,
  2802. set: setter,
  2803. configurable: true
  2804. });
  2805. } else if (npt.tagName !== "INPUT") {
  2806. valueGet = function () {
  2807. return this.textContent;
  2808. };
  2809. valueSet = function (value) {
  2810. this.textContent = value;
  2811. };
  2812. Object.defineProperty(npt, "value", {
  2813. get: getter,
  2814. set: setter,
  2815. configurable: true
  2816. });
  2817. }
  2818. } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
  2819. valueGet = npt.__lookupGetter__("value");
  2820. valueSet = npt.__lookupSetter__("value");
  2821. npt.__defineGetter__("value", getter);
  2822. npt.__defineSetter__("value", setter);
  2823. }
  2824. npt.inputmask.__valueGet = valueGet; //store native property getter
  2825. npt.inputmask.__valueSet = valueSet; //store native property setter
  2826. }
  2827. npt.inputmask._valueGet = function (overruleRTL) {
  2828. return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
  2829. };
  2830. npt.inputmask._valueSet = function (value, overruleRTL) { //null check is needed for IE8 => otherwise converts to "null"
  2831. valueSet.call(this.el, (value === null || value === undefined) ? "" : ((overruleRTL !== true && isRTL) ? value.split("").reverse().join("") : value));
  2832. };
  2833. if (valueGet === undefined) { //jquery.val fallback
  2834. valueGet = function () {
  2835. return this.value;
  2836. };
  2837. valueSet = function (value) {
  2838. this.value = value;
  2839. };
  2840. patchValhook(npt.type);
  2841. installNativeValueSetFallback(npt);
  2842. }
  2843. }
  2844. }
  2845. var elementType = input.getAttribute("type");
  2846. var isSupported = (input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1) || input.isContentEditable || input.tagName === "TEXTAREA";
  2847. if (!isSupported) {
  2848. if (input.tagName === "INPUT") {
  2849. var el = document.createElement("input");
  2850. el.setAttribute("type", elementType);
  2851. isSupported = el.type === "text"; //apply mask only if the type is not natively supported
  2852. el = null;
  2853. } else isSupported = "partial";
  2854. }
  2855. if (isSupported !== false) {
  2856. patchValueProperty(input);
  2857. }
  2858. return isSupported;
  2859. }
  2860. //unbind all events - to make sure that no other mask will interfere when re-masking
  2861. EventRuler.off(elem);
  2862. var isSupported = isElementTypeSupported(elem, opts);
  2863. if (isSupported !== false) {
  2864. el = elem;
  2865. $el = $(el);
  2866. if (opts.colorMask === true) {
  2867. initializeColorMask(el);
  2868. }
  2869. if (android) {
  2870. if (el.hasOwnProperty("inputmode")) {
  2871. el.inputmode = opts.inputmode;
  2872. el.setAttribute("inputmode", opts.inputmode);
  2873. }
  2874. if (opts.androidHack === "rtfm") {
  2875. if (opts.colorMask !== true) {
  2876. initializeColorMask(el);
  2877. }
  2878. el.type = "password";
  2879. }
  2880. }
  2881. if (isSupported === true) {
  2882. //bind events
  2883. EventRuler.on(el, "submit", EventHandlers.submitEvent);
  2884. EventRuler.on(el, "reset", EventHandlers.resetEvent);
  2885. EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
  2886. EventRuler.on(el, "blur", EventHandlers.blurEvent);
  2887. EventRuler.on(el, "focus", EventHandlers.focusEvent);
  2888. EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
  2889. if (opts.colorMask !== true)
  2890. EventRuler.on(el, "click", EventHandlers.clickEvent);
  2891. EventRuler.on(el, "dblclick", EventHandlers.dblclickEvent);
  2892. EventRuler.on(el, "paste", EventHandlers.pasteEvent);
  2893. EventRuler.on(el, "dragdrop", EventHandlers.pasteEvent);
  2894. EventRuler.on(el, "drop", EventHandlers.pasteEvent);
  2895. EventRuler.on(el, "cut", EventHandlers.cutEvent);
  2896. EventRuler.on(el, "complete", opts.oncomplete);
  2897. EventRuler.on(el, "incomplete", opts.onincomplete);
  2898. EventRuler.on(el, "cleared", opts.oncleared);
  2899. if (!android && opts.inputEventOnly !== true) {
  2900. EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
  2901. EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
  2902. }
  2903. EventRuler.on(el, "compositionstart", $.noop);
  2904. EventRuler.on(el, "compositionupdate", $.noop);
  2905. EventRuler.on(el, "compositionend", $.noop);
  2906. EventRuler.on(el, "keyup", $.noop);
  2907. EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
  2908. EventRuler.on(el, "beforeinput", $.noop); //https://github.com/w3c/input-events - to implement
  2909. }
  2910. EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
  2911. //apply mask
  2912. undoValue = getBufferTemplate().join(""); //initialize the buffer and getmasklength
  2913. if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
  2914. var initialValue = $.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true)) : el.inputmask._valueGet(true);
  2915. if (initialValue !== "") checkVal(el, true, false, isRTL ? initialValue.split("").reverse() : initialValue.split(""));
  2916. var buffer = getBuffer().slice();
  2917. // Wrap document.activeElement in a try/catch block since IE9 throw "Unspecified error" if document.activeElement is undefined when we are in an IFrame.
  2918. if (isComplete(buffer) === false) {
  2919. if (opts.clearIncomplete) {
  2920. resetMaskSet();
  2921. }
  2922. }
  2923. if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
  2924. if (getLastValidPosition() === -1) {
  2925. buffer = [];
  2926. } else {
  2927. clearOptionalTail(buffer);
  2928. }
  2929. }
  2930. writeBuffer(el, buffer);
  2931. if (document.activeElement === el) { //position the caret when in focus
  2932. caret(el, seekNext(getLastValidPosition()));
  2933. }
  2934. }
  2935. }
  2936. }
  2937. //action object
  2938. var valueBuffer;
  2939. if (actionObj !== undefined) {
  2940. switch (actionObj.action) {
  2941. case "isComplete":
  2942. el = actionObj.el;
  2943. return isComplete(getBuffer());
  2944. case "unmaskedvalue":
  2945. if (el === undefined || actionObj.value !== undefined) {
  2946. valueBuffer = actionObj.value;
  2947. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(valueBuffer, opts) || valueBuffer) : valueBuffer).split("");
  2948. checkVal(undefined, false, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2949. if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite(undefined, getBuffer(), 0, opts);
  2950. }
  2951. return unmaskedvalue(el);
  2952. case "mask":
  2953. mask(el);
  2954. break;
  2955. case "format":
  2956. valueBuffer = ($.isFunction(opts.onBeforeMask) ? (opts.onBeforeMask(actionObj.value, opts) || actionObj.value) : actionObj.value).split("");
  2957. checkVal(undefined, true, false, isRTL ? valueBuffer.reverse() : valueBuffer);
  2958. if (actionObj.metadata) {
  2959. return {
  2960. value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
  2961. metadata: maskScope.call(this, {
  2962. "action": "getmetadata"
  2963. }, maskset, opts)
  2964. };
  2965. }
  2966. return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
  2967. case "isValid":
  2968. if (actionObj.value) {
  2969. valueBuffer = actionObj.value.split("");
  2970. checkVal(undefined, true, true, isRTL ? valueBuffer.reverse() : valueBuffer);
  2971. } else {
  2972. actionObj.value = getBuffer().join("");
  2973. }
  2974. var buffer = getBuffer();
  2975. var rl = determineLastRequiredPosition(),
  2976. lmib = buffer.length - 1;
  2977. for (; lmib > rl; lmib--) {
  2978. if (isMask(lmib)) break;
  2979. }
  2980. buffer.splice(rl, lmib + 1 - rl);
  2981. return isComplete(buffer) && actionObj.value === getBuffer().join("");
  2982. case "getemptymask":
  2983. return getBufferTemplate().join("");
  2984. case "remove":
  2985. if (el && el.inputmask) {
  2986. $el = $(el);
  2987. //writeout the value
  2988. el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(true));
  2989. //unbind all events
  2990. EventRuler.off(el);
  2991. //restore the value property
  2992. var valueProperty;
  2993. if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
  2994. valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
  2995. if (valueProperty) {
  2996. if (el.inputmask.__valueGet) {
  2997. Object.defineProperty(el, "value", {
  2998. get: el.inputmask.__valueGet,
  2999. set: el.inputmask.__valueSet,
  3000. configurable: true
  3001. });
  3002. }
  3003. }
  3004. } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
  3005. if (el.inputmask.__valueGet) {
  3006. el.__defineGetter__("value", el.inputmask.__valueGet);
  3007. el.__defineSetter__("value", el.inputmask.__valueSet);
  3008. }
  3009. }
  3010. //clear data
  3011. el.inputmask = undefined;
  3012. }
  3013. return el;
  3014. break;
  3015. case "getmetadata":
  3016. if ($.isArray(maskset.metadata)) {
  3017. var maskTarget = getMaskTemplate(true, 0, false).join("");
  3018. $.each(maskset.metadata, function (ndx, mtdt) {
  3019. if (mtdt.mask === maskTarget) {
  3020. maskTarget = mtdt;
  3021. return false;
  3022. }
  3023. });
  3024. return maskTarget;
  3025. }
  3026. return maskset.metadata;
  3027. }
  3028. }
  3029. }
  3030. //make inputmask available
  3031. return Inputmask;
  3032. }
  3033. ))
  3034. ;