inputmask.js 106 KB

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