inputmask.js 111 KB

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