inputmask.js 185 KB

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