inputmask.js 110 KB

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