inputmask.js 120 KB

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