inputmask.js 104 KB

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