Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

inputmask.js 112KB

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