inputmask.js 104 KB

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