inputmask.js 110 KB

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