inputmask.js 104 KB

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