inputmask.js 105 KB

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