inputmask.js 178 KB

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