inputmask.js 120 KB

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