inputmask.js 177 KB

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