inputmask.js 174 KB

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