inputmask.js 184 KB

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