inputmask.js 100 KB

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