inputmask.js 106 KB

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