inputmask.js 176 KB

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