inputmask.js 120 KB

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