inputmask.numeric.extensions.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /*
  2. Input Mask plugin extensions
  3. http://github.com/RobinHerbots/inputmask
  4. Copyright (c) Robin Herbots
  5. Licensed under the MIT license
  6. */
  7. import { escapeRegex } from "../escapeRegex";
  8. import Inputmask from "../inputmask";
  9. import { keys } from "../keycode";
  10. import { seekNext } from "../positioning";
  11. const $ = Inputmask.dependencyLib;
  12. function autoEscape(txt, opts) {
  13. let escapedTxt = "";
  14. for (let i = 0; i < txt.length; i++) {
  15. if (
  16. Inputmask.prototype.definitions[txt.charAt(i)] ||
  17. opts.definitions[txt.charAt(i)] ||
  18. opts.optionalmarker[0] === txt.charAt(i) ||
  19. opts.optionalmarker[1] === txt.charAt(i) ||
  20. opts.quantifiermarker[0] === txt.charAt(i) ||
  21. opts.quantifiermarker[1] === txt.charAt(i) ||
  22. opts.groupmarker[0] === txt.charAt(i) ||
  23. opts.groupmarker[1] === txt.charAt(i) ||
  24. opts.alternatormarker === txt.charAt(i)
  25. ) {
  26. escapedTxt += "\\" + txt.charAt(i);
  27. } else {
  28. escapedTxt += txt.charAt(i);
  29. }
  30. }
  31. return escapedTxt;
  32. }
  33. function alignDigits(buffer, digits, opts, force) {
  34. if (buffer.length > 0 && digits > 0 && (!opts.digitsOptional || force)) {
  35. var radixPosition = buffer.indexOf(opts.radixPoint),
  36. negationBack = false;
  37. if (opts.negationSymbol.back === buffer[buffer.length - 1]) {
  38. negationBack = true;
  39. buffer.length--;
  40. }
  41. if (radixPosition === -1) {
  42. buffer.push(opts.radixPoint);
  43. radixPosition = buffer.length - 1;
  44. }
  45. for (let i = 1; i <= digits; i++) {
  46. if (!isFinite(buffer[radixPosition + i])) {
  47. buffer[radixPosition + i] = "0";
  48. }
  49. }
  50. }
  51. if (negationBack) buffer.push(opts.negationSymbol.back);
  52. return buffer;
  53. }
  54. function findValidator(symbol, maskset) {
  55. let posNdx = 0;
  56. if (symbol === "+") {
  57. posNdx = seekNext.call(this, maskset.validPositions.length - 1);
  58. }
  59. for (let tstNdx in maskset.tests) {
  60. tstNdx = parseInt(tstNdx);
  61. if (tstNdx >= posNdx) {
  62. for (
  63. let ndx = 0, ndxl = maskset.tests[tstNdx].length;
  64. ndx < ndxl;
  65. ndx++
  66. ) {
  67. if (
  68. (maskset.validPositions[tstNdx] === undefined || symbol === "-") &&
  69. maskset.tests[tstNdx][ndx].match.def === symbol
  70. ) {
  71. return (
  72. tstNdx +
  73. (maskset.validPositions[tstNdx] !== undefined && symbol !== "-"
  74. ? 1
  75. : 0)
  76. );
  77. }
  78. }
  79. }
  80. }
  81. return posNdx;
  82. }
  83. function findValid(symbol, maskset) {
  84. let ret = -1;
  85. for (let ndx = 0, vpl = maskset.validPositions.length; ndx < vpl; ndx++) {
  86. const tst = maskset.validPositions[ndx];
  87. if (tst && tst.match.def === symbol) {
  88. ret = ndx;
  89. break;
  90. }
  91. }
  92. return ret;
  93. }
  94. function parseMinMaxOptions(opts) {
  95. if (opts.parseMinMaxOptions === undefined) {
  96. // convert min and max options
  97. if (opts.min !== null) {
  98. opts.min = opts.min
  99. .toString()
  100. .replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
  101. if (opts.radixPoint === ",")
  102. opts.min = opts.min.replace(opts.radixPoint, ".");
  103. opts.min = isFinite(opts.min) ? parseFloat(opts.min) : NaN;
  104. if (isNaN(opts.min)) opts.min = Number.MIN_VALUE;
  105. }
  106. if (opts.max !== null) {
  107. opts.max = opts.max
  108. .toString()
  109. .replace(new RegExp(escapeRegex(opts.groupSeparator), "g"), "");
  110. if (opts.radixPoint === ",")
  111. opts.max = opts.max.replace(opts.radixPoint, ".");
  112. opts.max = isFinite(opts.max) ? parseFloat(opts.max) : NaN;
  113. if (isNaN(opts.max)) opts.max = Number.MAX_VALUE;
  114. }
  115. opts.parseMinMaxOptions = "done";
  116. }
  117. }
  118. function genMask(opts) {
  119. opts.repeat = 0;
  120. // treat equal separator and radixpoint
  121. if (
  122. opts.groupSeparator === opts.radixPoint &&
  123. opts.digits &&
  124. opts.digits !== "0"
  125. ) {
  126. if (opts.radixPoint === ".") {
  127. opts.groupSeparator = ",";
  128. } else if (opts.radixPoint === ",") {
  129. opts.groupSeparator = ".";
  130. } else {
  131. opts.groupSeparator = "";
  132. }
  133. }
  134. // prevent conflict with default skipOptionalPartCharacter
  135. if (opts.groupSeparator === " ") {
  136. opts.skipOptionalPartCharacter = undefined;
  137. }
  138. // enforce placeholder to single
  139. if (opts.placeholder.length > 1) {
  140. opts.placeholder = opts.placeholder.charAt(0);
  141. }
  142. // only allow radixfocus when placeholder = 0
  143. if (opts.positionCaretOnClick === "radixFocus" && opts.placeholder === "") {
  144. opts.positionCaretOnClick = "lvp";
  145. }
  146. let decimalDef = "0",
  147. radixPointDef = opts.radixPoint;
  148. if (opts.numericInput === true && opts.__financeInput === undefined) {
  149. // finance people input style
  150. decimalDef = "1";
  151. opts.positionCaretOnClick =
  152. opts.positionCaretOnClick === "radixFocus"
  153. ? "lvp"
  154. : opts.positionCaretOnClick;
  155. opts.digitsOptional = false;
  156. if (isNaN(opts.digits))
  157. opts.digits =
  158. opts.digits.indexOf(",") !== -1 ? opts.digits.split(",")[0] : 2;
  159. opts._radixDance = false;
  160. radixPointDef = opts.radixPoint === "," ? "?" : "!";
  161. if (
  162. opts.radixPoint !== "" &&
  163. opts.definitions[radixPointDef] === undefined
  164. ) {
  165. // update separator definition
  166. opts.definitions[radixPointDef] = {};
  167. opts.definitions[radixPointDef].validator = "[" + opts.radixPoint + "]";
  168. opts.definitions[radixPointDef].placeholder = opts.radixPoint;
  169. opts.definitions[radixPointDef].static = true;
  170. opts.definitions[radixPointDef].generated = true; // forced marker as generated input
  171. }
  172. } else {
  173. opts.__financeInput = false; // needed to keep original selection when remasking
  174. opts.numericInput = true;
  175. }
  176. let mask = "[+]",
  177. altMask;
  178. mask += autoEscape(opts.prefix, opts);
  179. if (opts.groupSeparator !== "") {
  180. if (opts.definitions[opts.groupSeparator] === undefined) {
  181. // update separator definition
  182. opts.definitions[opts.groupSeparator] = {};
  183. opts.definitions[opts.groupSeparator].validator =
  184. "[" + opts.groupSeparator + "]";
  185. opts.definitions[opts.groupSeparator].placeholder = opts.groupSeparator;
  186. opts.definitions[opts.groupSeparator].static = true;
  187. opts.definitions[opts.groupSeparator].generated = true; // forced marker as generated input
  188. }
  189. mask += opts._mask(opts);
  190. } else {
  191. mask += "9{+}";
  192. }
  193. if (opts.digits !== undefined && opts.digits !== 0) {
  194. const dq = opts.digits.toString().split(",");
  195. if (isFinite(dq[0]) && dq[1] && isFinite(dq[1])) {
  196. mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
  197. } else if (isNaN(opts.digits) || parseInt(opts.digits) > 0) {
  198. if (opts.digitsOptional || opts.jitMasking) {
  199. altMask = mask + radixPointDef + decimalDef + "{0," + opts.digits + "}";
  200. // mask += "[" + opts.radixPoint + "]";
  201. opts.keepStatic = true;
  202. } else {
  203. mask += radixPointDef + decimalDef + "{" + opts.digits + "}";
  204. }
  205. }
  206. } else {
  207. opts.inputmode = "numeric";
  208. }
  209. mask += autoEscape(opts.suffix, opts);
  210. mask += "[-]";
  211. if (altMask) {
  212. mask = [altMask + autoEscape(opts.suffix, opts) + "[-]", mask];
  213. }
  214. opts.greedy = false; // enforce greedy false
  215. parseMinMaxOptions(opts);
  216. if (opts.radixPoint !== "" && opts.substituteRadixPoint)
  217. opts.substitutes[opts.radixPoint == "." ? "," : "."] = opts.radixPoint;
  218. // console.log(mask);
  219. return mask;
  220. }
  221. function handleRadixDance(pos, c, radixPos, maskset, opts) {
  222. if (opts._radixDance && opts.numericInput && c !== opts.negationSymbol.back) {
  223. if (
  224. pos <= radixPos &&
  225. (radixPos > 0 || c == opts.radixPoint) &&
  226. (maskset.validPositions[pos - 1] === undefined ||
  227. maskset.validPositions[pos - 1].input !== opts.negationSymbol.back)
  228. ) {
  229. pos -= 1;
  230. }
  231. }
  232. return pos;
  233. }
  234. function decimalValidator(chrs, maskset, pos, strict, opts) {
  235. const radixPos = maskset.buffer
  236. ? maskset.buffer.indexOf(opts.radixPoint)
  237. : -1,
  238. result =
  239. (radixPos !== -1 || (strict && opts.jitMasking)) &&
  240. new RegExp(opts.definitions["9"].validator).test(chrs);
  241. if (
  242. !strict &&
  243. opts._radixDance &&
  244. radixPos !== -1 &&
  245. result &&
  246. maskset.validPositions[radixPos] == undefined
  247. ) {
  248. return {
  249. insert: {
  250. pos: radixPos === pos ? radixPos + 1 : radixPos,
  251. c: opts.radixPoint
  252. },
  253. pos
  254. };
  255. }
  256. return result;
  257. }
  258. function checkForLeadingZeroes(buffer, opts) {
  259. // check leading zeros
  260. let numberMatches = new RegExp(
  261. "(^" +
  262. (opts.negationSymbol.front !== ""
  263. ? escapeRegex(opts.negationSymbol.front) + "?"
  264. : "") +
  265. escapeRegex(opts.prefix) +
  266. ")(.*)(" +
  267. escapeRegex(opts.suffix) +
  268. (opts.negationSymbol.back != ""
  269. ? escapeRegex(opts.negationSymbol.back) + "?"
  270. : "") +
  271. "$)"
  272. ).exec(buffer.slice().reverse().join("")),
  273. number = numberMatches ? numberMatches[2] : "",
  274. leadingzeroes = false;
  275. if (number) {
  276. number = number.split(opts.radixPoint.charAt(0))[0];
  277. leadingzeroes = new RegExp("^[0" + opts.groupSeparator + "]*").exec(number);
  278. }
  279. return leadingzeroes &&
  280. (leadingzeroes[0].length > 1 ||
  281. (leadingzeroes[0].length > 0 && leadingzeroes[0].length < number.length))
  282. ? leadingzeroes
  283. : false;
  284. }
  285. // number aliases
  286. Inputmask.extendAliases({
  287. numeric: {
  288. mask: genMask,
  289. _mask: function (opts) {
  290. return "(" + opts.groupSeparator + "999){+|1}";
  291. },
  292. digits: "*", // number of fractionalDigits
  293. digitsOptional: true,
  294. enforceDigitsOnBlur: false,
  295. radixPoint: ".",
  296. positionCaretOnClick: "radixFocus",
  297. _radixDance: true,
  298. groupSeparator: "",
  299. allowMinus: true,
  300. negationSymbol: {
  301. front: "-", // "("
  302. back: "" // ")"
  303. },
  304. prefix: "",
  305. suffix: "",
  306. min: null, // minimum value
  307. max: null, // maximum value
  308. SetMaxOnOverflow: false,
  309. step: 1,
  310. inputType: "text", // number ~ specify that values which are set are in textform (radix point is same as in the options) or in numberform (radixpoint = .)
  311. unmaskAsNumber: false,
  312. roundingFN: Math.round, // Math.floor , fn(x)
  313. inputmode: "decimal",
  314. shortcuts: { k: "1000", m: "1000000" },
  315. // global options
  316. placeholder: "0",
  317. greedy: false,
  318. rightAlign: true,
  319. insertMode: true,
  320. autoUnmask: false,
  321. skipOptionalPartCharacter: "",
  322. usePrototypeDefinitions: false,
  323. stripLeadingZeroes: true,
  324. substituteRadixPoint: true,
  325. definitions: {
  326. 0: {
  327. validator: decimalValidator
  328. },
  329. 1: {
  330. validator: decimalValidator,
  331. definitionSymbol: "9"
  332. },
  333. 9: {
  334. // \uFF11-\uFF19 #1606
  335. validator: "[0-9\uFF10-\uFF19\u0660-\u0669\u06F0-\u06F9]",
  336. definitionSymbol: "*"
  337. },
  338. "+": {
  339. validator: function (chrs, maskset, pos, strict, opts) {
  340. return (
  341. opts.allowMinus &&
  342. (chrs === "-" || chrs === opts.negationSymbol.front)
  343. );
  344. }
  345. },
  346. "-": {
  347. validator: function (chrs, maskset, pos, strict, opts) {
  348. return opts.allowMinus && chrs === opts.negationSymbol.back;
  349. }
  350. }
  351. },
  352. preValidation: function (
  353. buffer,
  354. pos,
  355. c,
  356. isSelection,
  357. opts,
  358. maskset,
  359. caretPos,
  360. strict
  361. ) {
  362. const inputmask = this;
  363. if (opts.__financeInput !== false && c === opts.radixPoint) return false;
  364. const radixPos = buffer.indexOf(opts.radixPoint),
  365. initPos = pos;
  366. pos = handleRadixDance(pos, c, radixPos, maskset, opts);
  367. if (c === "-" || c === opts.negationSymbol.front) {
  368. if (opts.allowMinus !== true) return false;
  369. let isNegative = false,
  370. front = findValid("+", maskset),
  371. back = findValid("-", maskset);
  372. if (front !== -1) {
  373. isNegative = [front];
  374. if (back !== -1) isNegative.push(back);
  375. }
  376. return isNegative !== false
  377. ? {
  378. remove: isNegative,
  379. caret: initPos - opts.negationSymbol.back.length
  380. }
  381. : {
  382. insert: [
  383. {
  384. pos: findValidator.call(inputmask, "+", maskset),
  385. c: opts.negationSymbol.front,
  386. fromIsValid: true
  387. },
  388. {
  389. pos: findValidator.call(inputmask, "-", maskset),
  390. c: opts.negationSymbol.back,
  391. fromIsValid: undefined
  392. }
  393. ],
  394. caret: initPos + opts.negationSymbol.back.length
  395. };
  396. }
  397. if (c === opts.groupSeparator) {
  398. return { caret: initPos };
  399. }
  400. if (strict) return true;
  401. if (
  402. radixPos !== -1 &&
  403. opts._radixDance === true &&
  404. isSelection === false &&
  405. c === opts.radixPoint &&
  406. opts.digits !== undefined &&
  407. (isNaN(opts.digits) || parseInt(opts.digits) > 0) &&
  408. radixPos !== pos
  409. ) {
  410. const radixValidatorPos = findValidator.call(
  411. inputmask,
  412. opts.radixPoint,
  413. maskset
  414. );
  415. if (maskset.validPositions[radixValidatorPos]) {
  416. maskset.validPositions[radixValidatorPos].generatedInput =
  417. maskset.validPositions[radixValidatorPos].generated || false;
  418. }
  419. return {
  420. caret:
  421. opts._radixDance && pos === radixPos - 1 ? radixPos + 1 : radixPos
  422. };
  423. }
  424. if (opts.__financeInput === false) {
  425. if (isSelection) {
  426. if (opts.digitsOptional) {
  427. return { rewritePosition: caretPos.end };
  428. } else if (!opts.digitsOptional) {
  429. if (caretPos.begin > radixPos && caretPos.end <= radixPos) {
  430. if (c === opts.radixPoint) {
  431. return {
  432. insert: { pos: radixPos + 1, c: "0", fromIsValid: true },
  433. rewritePosition: radixPos
  434. };
  435. } else {
  436. return { rewritePosition: radixPos + 1 };
  437. }
  438. } else if (caretPos.begin < radixPos) {
  439. return { rewritePosition: caretPos.begin - 1 };
  440. }
  441. }
  442. } else if (
  443. !opts.showMaskOnHover &&
  444. !opts.showMaskOnFocus &&
  445. !opts.digitsOptional &&
  446. opts.digits > 0 &&
  447. this.__valueGet.call(this.el) === ""
  448. ) {
  449. return { rewritePosition: radixPos };
  450. }
  451. }
  452. return { rewritePosition: pos };
  453. },
  454. postValidation: function (
  455. buffer,
  456. pos,
  457. c,
  458. currentResult,
  459. opts,
  460. maskset,
  461. strict,
  462. fromCheckval,
  463. fromAlternate
  464. ) {
  465. if (currentResult === false) return currentResult;
  466. if (strict) return true;
  467. if (opts.min !== null || opts.max !== null) {
  468. const unmasked = opts.onUnMask(
  469. buffer.slice().reverse().join(""),
  470. undefined,
  471. $.extend({}, opts, {
  472. unmaskAsNumber: true
  473. })
  474. );
  475. if (
  476. opts.min !== null &&
  477. unmasked < opts.min &&
  478. fromAlternate !== true &&
  479. (unmasked.toString().length > opts.min.toString().length || // > instead of >= because we want to allow to type a bigger number
  480. buffer[0] === opts.radixPoint || // disallow radixpoint when value is smaller than min
  481. unmasked < 0)
  482. ) {
  483. return false;
  484. // return {
  485. // refreshFromBuffer: true,
  486. // buffer: alignDigits(opts.min.toString().replace(".", opts.radixPoint).split(""), opts.digits, opts).reverse()
  487. // };
  488. }
  489. if (opts.max !== null && opts.max >= 0 && unmasked > opts.max) {
  490. return opts.SetMaxOnOverflow
  491. ? {
  492. refreshFromBuffer: true,
  493. buffer: alignDigits(
  494. opts.max.toString().replace(".", opts.radixPoint).split(""),
  495. opts.digits,
  496. opts
  497. ).reverse()
  498. }
  499. : false;
  500. }
  501. }
  502. return currentResult;
  503. },
  504. onUnMask: function (maskedValue, unmaskedValue, opts) {
  505. if (unmaskedValue === "" && opts.nullable === true) {
  506. return unmaskedValue;
  507. }
  508. let processValue = maskedValue.replace(opts.prefix, "");
  509. processValue = processValue.replace(opts.suffix, "");
  510. processValue = processValue.replace(
  511. new RegExp(escapeRegex(opts.groupSeparator), "g"),
  512. ""
  513. );
  514. if (opts.placeholder.charAt(0) !== "") {
  515. processValue = processValue.replace(
  516. new RegExp(opts.placeholder.charAt(0), "g"),
  517. "0"
  518. );
  519. }
  520. if (opts.unmaskAsNumber) {
  521. if (
  522. opts.radixPoint !== "" &&
  523. processValue.indexOf(opts.radixPoint) !== -1
  524. )
  525. processValue = processValue.replace(
  526. escapeRegex.call(this, opts.radixPoint),
  527. "."
  528. );
  529. processValue = processValue.replace(
  530. new RegExp("^" + escapeRegex(opts.negationSymbol.front)),
  531. "-"
  532. );
  533. processValue = processValue.replace(
  534. new RegExp(escapeRegex(opts.negationSymbol.back) + "$"),
  535. ""
  536. );
  537. return Number(processValue);
  538. }
  539. return processValue;
  540. },
  541. isComplete: function (buffer, opts) {
  542. let maskedValue = (
  543. opts.numericInput ? buffer.slice().reverse() : buffer
  544. ).join("");
  545. maskedValue = maskedValue.replace(
  546. new RegExp("^" + escapeRegex(opts.negationSymbol.front)),
  547. "-"
  548. );
  549. maskedValue = maskedValue.replace(
  550. new RegExp(escapeRegex(opts.negationSymbol.back) + "$"),
  551. ""
  552. );
  553. maskedValue = maskedValue.replace(opts.prefix, "");
  554. maskedValue = maskedValue.replace(opts.suffix, "");
  555. maskedValue = maskedValue.replace(
  556. new RegExp(escapeRegex(opts.groupSeparator) + "([0-9]{3})", "g"),
  557. "$1"
  558. );
  559. if (opts.radixPoint === ",")
  560. maskedValue = maskedValue.replace(escapeRegex(opts.radixPoint), ".");
  561. return isFinite(maskedValue);
  562. },
  563. onBeforeMask: function (initialValue, opts) {
  564. initialValue = initialValue ?? "";
  565. const radixPoint = opts.radixPoint || ",";
  566. if (isFinite(opts.digits)) opts.digits = parseInt(opts.digits);
  567. if (
  568. (typeof initialValue === "number" || opts.inputType === "number") &&
  569. radixPoint !== ""
  570. ) {
  571. initialValue = initialValue.toString().replace(".", radixPoint);
  572. }
  573. const isNegative =
  574. initialValue.charAt(0) === "-" ||
  575. initialValue.charAt(0) === opts.negationSymbol.front,
  576. valueParts = initialValue.split(radixPoint),
  577. integerPart = valueParts[0].replace(/[^\-0-9]/g, ""),
  578. decimalPart =
  579. valueParts.length > 1 ? valueParts[1].replace(/[^0-9]/g, "") : "",
  580. forceDigits = valueParts.length > 1;
  581. initialValue =
  582. integerPart +
  583. (decimalPart !== "" ? radixPoint + decimalPart : decimalPart);
  584. let digits = 0;
  585. if (radixPoint !== "") {
  586. digits = !opts.digitsOptional
  587. ? opts.digits
  588. : opts.digits < decimalPart.length
  589. ? opts.digits
  590. : decimalPart.length;
  591. if (decimalPart !== "" || !opts.digitsOptional) {
  592. const digitsFactor = Math.pow(10, digits || 1);
  593. // make the initialValue a valid javascript number for the parsefloat
  594. initialValue = initialValue.replace(escapeRegex(radixPoint), ".");
  595. if (!isNaN(parseFloat(initialValue))) {
  596. initialValue = (
  597. opts.roundingFN(parseFloat(initialValue) * digitsFactor) /
  598. digitsFactor
  599. ).toFixed(digits);
  600. }
  601. initialValue = initialValue.toString().replace(".", radixPoint);
  602. }
  603. }
  604. // this needs to be in a separate part and not directly in decimalPart to allow rounding
  605. if (opts.digits === 0 && initialValue.indexOf(radixPoint) !== -1) {
  606. initialValue = initialValue.substring(
  607. 0,
  608. initialValue.indexOf(radixPoint)
  609. );
  610. }
  611. if (initialValue !== "" && (opts.min !== null || opts.max !== null)) {
  612. const numberValue = initialValue.toString().replace(radixPoint, ".");
  613. if (opts.min !== null && numberValue < opts.min) {
  614. initialValue = opts.min.toString().replace(".", radixPoint);
  615. } else if (opts.max !== null && numberValue > opts.max) {
  616. initialValue = opts.max.toString().replace(".", radixPoint);
  617. }
  618. }
  619. if (isNegative && initialValue.charAt(0) !== "-") {
  620. initialValue = "-" + initialValue;
  621. }
  622. return alignDigits(
  623. initialValue.toString().split(""),
  624. digits,
  625. opts,
  626. forceDigits
  627. ).join("");
  628. },
  629. onBeforeWrite: function (e, buffer, caretPos, opts) {
  630. function stripBuffer(buffer, stripRadix) {
  631. if (opts.__financeInput !== false || stripRadix) {
  632. var position = buffer.indexOf(opts.radixPoint);
  633. if (position !== -1) {
  634. buffer.splice(position, 1);
  635. }
  636. }
  637. if (opts.groupSeparator !== "") {
  638. while ((position = buffer.indexOf(opts.groupSeparator)) !== -1) {
  639. buffer.splice(position, 1);
  640. }
  641. }
  642. return buffer;
  643. }
  644. let result, leadingzeroes;
  645. if (
  646. opts.stripLeadingZeroes &&
  647. (leadingzeroes = checkForLeadingZeroes(buffer, opts))
  648. ) {
  649. const caretNdx =
  650. buffer
  651. .join("")
  652. .lastIndexOf(leadingzeroes[0].split("").reverse().join("")) -
  653. (leadingzeroes[0] == leadingzeroes.input ? 0 : 1),
  654. offset = leadingzeroes[0] == leadingzeroes.input ? 1 : 0;
  655. for (let i = leadingzeroes[0].length - offset; i > 0; i--) {
  656. this.maskset.validPositions.splice(caretNdx + i, 1);
  657. delete buffer[caretNdx + i];
  658. }
  659. }
  660. if (e) {
  661. switch (e.type) {
  662. case "blur":
  663. case "checkval":
  664. if (opts.min !== null || opts.max !== null) {
  665. const unmasked = opts.onUnMask(
  666. buffer.slice().reverse().join(""),
  667. undefined,
  668. $.extend({}, opts, {
  669. unmaskAsNumber: true
  670. })
  671. );
  672. if (
  673. opts.min !== null &&
  674. unmasked < opts.min &&
  675. buffer.join() !== ""
  676. ) {
  677. return {
  678. refreshFromBuffer: true,
  679. buffer: alignDigits(
  680. opts.min.toString().replace(".", opts.radixPoint).split(""),
  681. opts.digits,
  682. opts
  683. ).reverse()
  684. };
  685. } else if (opts.max !== null && unmasked > opts.max) {
  686. return {
  687. refreshFromBuffer: true,
  688. buffer: alignDigits(
  689. opts.max.toString().replace(".", opts.radixPoint).split(""),
  690. opts.digits,
  691. opts
  692. ).reverse()
  693. };
  694. }
  695. }
  696. if (buffer[buffer.length - 1] === opts.negationSymbol.front) {
  697. // strip negation symbol on blur when value is 0
  698. const nmbrMtchs = new RegExp(
  699. "(^" +
  700. (opts.negationSymbol.front != ""
  701. ? escapeRegex(opts.negationSymbol.front) + "?"
  702. : "") +
  703. escapeRegex(opts.prefix) +
  704. ")(.*)(" +
  705. escapeRegex(opts.suffix) +
  706. (opts.negationSymbol.back != ""
  707. ? escapeRegex(opts.negationSymbol.back) + "?"
  708. : "") +
  709. "$)"
  710. ).exec(stripBuffer(buffer.slice(), true).reverse().join("")),
  711. number = nmbrMtchs ? nmbrMtchs[2] : "";
  712. if (number == 0) {
  713. result = { refreshFromBuffer: true, buffer: [0] };
  714. }
  715. } else if (opts.radixPoint !== "") {
  716. // strip radixpoint on blur when it is the latest char
  717. const radixNDX = buffer.indexOf(opts.radixPoint);
  718. if (radixNDX === opts.suffix.length) {
  719. if (result && result.buffer) {
  720. result.buffer.splice(0, 1 + opts.suffix.length);
  721. } else {
  722. buffer.splice(0, 1 + opts.suffix.length);
  723. result = {
  724. refreshFromBuffer: true,
  725. buffer: stripBuffer(buffer)
  726. };
  727. }
  728. }
  729. }
  730. if (opts.enforceDigitsOnBlur) {
  731. result = result || {};
  732. const bffr = ((result && result.buffer) || buffer)
  733. .slice()
  734. .reverse();
  735. result.refreshFromBuffer = true;
  736. result.buffer = alignDigits(
  737. bffr,
  738. opts.digits,
  739. opts,
  740. true
  741. ).reverse();
  742. }
  743. }
  744. }
  745. return result;
  746. },
  747. onKeyDown: function (e, buffer, caretPos, opts) {
  748. let $input = $(this),
  749. bffr;
  750. if (e.location != 3) {
  751. let pattern,
  752. c = e.key;
  753. if ((pattern = opts.shortcuts && opts.shortcuts[c])) {
  754. if (pattern.length > 1) {
  755. this.inputmask.__valueSet.call(
  756. this,
  757. parseFloat(this.inputmask.unmaskedvalue()) * parseInt(pattern)
  758. );
  759. $input.trigger("setvalue");
  760. return false;
  761. }
  762. }
  763. }
  764. if (e.ctrlKey) {
  765. switch (e.key) {
  766. case keys.ArrowUp:
  767. this.inputmask.__valueSet.call(
  768. this,
  769. parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step)
  770. );
  771. $input.trigger("setvalue");
  772. return false;
  773. case keys.ArrowDown:
  774. this.inputmask.__valueSet.call(
  775. this,
  776. parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step)
  777. );
  778. $input.trigger("setvalue");
  779. return false;
  780. }
  781. }
  782. if (
  783. !e.shiftKey &&
  784. (e.key === keys.Delete ||
  785. e.key === keys.Backspace ||
  786. e.key === keys.BACKSPACE_SAFARI) &&
  787. caretPos.begin !== buffer.length
  788. ) {
  789. if (
  790. buffer[e.key === keys.Delete ? caretPos.begin - 1 : caretPos.end] ===
  791. opts.negationSymbol.front
  792. ) {
  793. bffr = buffer.slice().reverse();
  794. if (opts.negationSymbol.front !== "") bffr.shift();
  795. if (opts.negationSymbol.back !== "") bffr.pop();
  796. $input.trigger("setvalue", [bffr.join(""), caretPos.begin]);
  797. return false;
  798. } else if (opts._radixDance === true) {
  799. const radixPos = buffer.indexOf(opts.radixPoint);
  800. if (!opts.digitsOptional) {
  801. if (
  802. radixPos !== -1 &&
  803. (caretPos.begin < radixPos ||
  804. caretPos.end < radixPos ||
  805. (e.key === keys.Delete &&
  806. (caretPos.begin === radixPos ||
  807. caretPos.begin - 1 === radixPos)))
  808. ) {
  809. let restoreCaretPos;
  810. if (caretPos.begin === caretPos.end) {
  811. // only adjust when not a selection
  812. if (e.key === keys.Backspace || e.key === keys.BACKSPACE_SAFARI)
  813. caretPos.begin++;
  814. else if (
  815. e.key === keys.Delete &&
  816. caretPos.begin - 1 === radixPos
  817. ) {
  818. restoreCaretPos = $.extend({}, caretPos);
  819. caretPos.begin--;
  820. caretPos.end--;
  821. }
  822. }
  823. bffr = buffer.slice().reverse();
  824. bffr.splice(
  825. bffr.length - caretPos.begin,
  826. caretPos.begin - caretPos.end + 1
  827. );
  828. // console.log(caretPos);
  829. bffr = alignDigits(bffr, opts.digits, opts).join("");
  830. if (restoreCaretPos) {
  831. caretPos = restoreCaretPos;
  832. }
  833. $input.trigger("setvalue", [
  834. bffr,
  835. caretPos.begin >= bffr.length ? radixPos + 1 : caretPos.begin
  836. ]);
  837. return false;
  838. }
  839. } else if (radixPos === 0) {
  840. bffr = buffer.slice().reverse();
  841. bffr.pop();
  842. $input.trigger("setvalue", [
  843. bffr.join(""),
  844. caretPos.begin >= bffr.length ? bffr.length : caretPos.begin
  845. ]);
  846. return false;
  847. }
  848. }
  849. }
  850. }
  851. },
  852. currency: {
  853. prefix: "", // "$ ",
  854. groupSeparator: ",",
  855. alias: "numeric",
  856. digits: 2,
  857. digitsOptional: false
  858. },
  859. decimal: {
  860. alias: "numeric"
  861. },
  862. integer: {
  863. alias: "numeric",
  864. inputmode: "numeric",
  865. digits: 0
  866. },
  867. percentage: {
  868. alias: "numeric",
  869. min: 0,
  870. max: 100,
  871. suffix: " %",
  872. digits: 0,
  873. allowMinus: false
  874. },
  875. indianns: {
  876. // indian numbering system
  877. alias: "numeric",
  878. _mask: function (opts) {
  879. return (
  880. "(" +
  881. opts.groupSeparator +
  882. "99){*|1}(" +
  883. opts.groupSeparator +
  884. "999){1|1}"
  885. );
  886. },
  887. groupSeparator: ",",
  888. radixPoint: ".",
  889. placeholder: "0",
  890. digits: 2,
  891. digitsOptional: false
  892. }
  893. });