jquery.inputmask.numeric.extensions.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. Input Mask plugin extensions
  3. http://github.com/RobinHerbots/jquery.inputmask
  4. Copyright (c) 2010 - 2014 Robin Herbots
  5. Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
  6. Version: 0.0.0
  7. Optional extensions on the jquery.inputmask base
  8. */
  9. (function ($) {
  10. //number aliases
  11. $.extend($.inputmask.defaults.aliases, {
  12. 'numeric': {
  13. mask: function (opts) {
  14. function autoEscape(txt) {
  15. var escapedTxt = "";
  16. for (var i = 0; i < txt.length; i++) {
  17. escapedTxt += opts.definitions[txt[i]] ? "\\" + txt[i] : txt[i];
  18. }
  19. return escapedTxt;
  20. }
  21. if (opts.repeat !== 0 && isNaN(opts.integerDigits)) {
  22. opts.integerDigits = opts.repeat;
  23. }
  24. opts.repeat = 0;
  25. if (opts.groupSeparator == opts.radixPoint) { //treat equal separator and radixpoint
  26. if (opts.radixPoint == ".")
  27. opts.groupSeparator = ",";
  28. else if (opts.radixPoint == ",")
  29. opts.groupSeparator = ".";
  30. else opts.groupSeparator = "";
  31. }
  32. if (opts.groupSeparator === " ") { //prevent conflict with default skipOptionalPartCharacter
  33. opts.skipOptionalPartCharacter = undefined;
  34. }
  35. opts.autoGroup = opts.autoGroup && opts.groupSeparator != "";
  36. if (opts.autoGroup) {
  37. if (typeof opts.groupSize == "string" && isFinite(opts.groupSize)) opts.groupSize = parseInt(opts.groupSize);
  38. if (isFinite(opts.integerDigits)) {
  39. var seps = Math.floor(opts.integerDigits / opts.groupSize);
  40. var mod = opts.integerDigits % opts.groupSize;
  41. opts.integerDigits = parseInt(opts.integerDigits) + (mod == 0 ? seps - 1 : seps);
  42. }
  43. }
  44. //only allow radixfocus when placeholder = 0
  45. opts.radixFocus = opts.radixFocus && opts.placeholder == "0";
  46. opts.definitions[";"] = opts.definitions["~"]; //clone integer def for decimals
  47. var mask = autoEscape(opts.prefix);
  48. mask += "[+]";
  49. mask += "~{1," + opts.integerDigits + "}";
  50. if (opts.digits != undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) {
  51. if (opts.digitsOptional)
  52. mask += "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]";
  53. else mask += (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}";
  54. }
  55. mask += autoEscape(opts.suffix);
  56. mask += "[-]";
  57. opts.greedy = false; //enforce greedy false
  58. return mask;
  59. },
  60. placeholder: "",
  61. greedy: false,
  62. digits: "*", //number of fractionalDigits
  63. digitsOptional: true,
  64. groupSeparator: "",//",", // | "."
  65. radixPoint: ".",
  66. radixFocus: true,
  67. groupSize: 3,
  68. autoGroup: false,
  69. allowPlus: true,
  70. allowMinus: true,
  71. negationSymbol: {
  72. front: "-", //"("
  73. back: "" //")"
  74. },
  75. integerDigits: "+", //number of integerDigits
  76. prefix: "",
  77. suffix: "",
  78. rightAlign: true,
  79. decimalProtect: true, //do not allow assumption of decimals input without entering the radixpoint
  80. min: undefined, //minimum value
  81. max: undefined, //maximum value
  82. postFormat: function (buffer, pos, reformatOnly, opts) { //this needs to be removed // this is crap
  83. var suffixStripped = false;
  84. if (buffer.length >= opts.suffix.length && buffer.join('').indexOf(opts.suffix) == (buffer.length - opts.suffix.length)) {
  85. buffer.length = buffer.length - opts.suffix.length; //strip suffix
  86. suffixStripped = true;
  87. }
  88. //position overflow corrections
  89. pos = pos >= buffer.length ? buffer.length - 1 : (pos < opts.prefix.length ? opts.prefix.length : pos);
  90. var needsRefresh = false, charAtPos = buffer[pos];
  91. if (opts.groupSeparator == "" ||
  92. ($.inArray(opts.radixPoint, buffer) != -1 && pos >= $.inArray(opts.radixPoint, buffer)) ||
  93. new RegExp('[-\+]').test(charAtPos)
  94. ) {
  95. if (suffixStripped) {
  96. for (var i = 0, l = opts.suffix.length; i < l; i++) {
  97. buffer[buffer.length + i] = opts.suffix.charAt(i);
  98. }
  99. }
  100. return { pos: pos };
  101. }
  102. var cbuf = buffer.slice();
  103. if (charAtPos == opts.groupSeparator) {
  104. cbuf.splice(pos--, 1);
  105. charAtPos = cbuf[pos];
  106. }
  107. if (reformatOnly) cbuf[pos] = "?"; else cbuf.splice(pos, 0, "?"); //set position indicator
  108. var bufVal = cbuf.join(''), bufValOrigin = bufVal;
  109. if (bufVal.length > 0 && opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
  110. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  111. needsRefresh = bufVal.indexOf(opts.groupSeparator) == 0;
  112. bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
  113. var radixSplit = bufVal.split(opts.radixPoint);
  114. bufVal = opts.radixPoint == "" ? bufVal : radixSplit[0];
  115. if (bufVal != (opts.prefix + "?0") && bufVal.length >= (opts.groupSize + opts.prefix.length)) {
  116. //needsRefresh = true;
  117. var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
  118. while (reg.test(bufVal)) {
  119. bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
  120. bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
  121. }
  122. }
  123. if (opts.radixPoint != "" && radixSplit.length > 1)
  124. bufVal += opts.radixPoint + radixSplit[1];
  125. }
  126. needsRefresh = bufValOrigin != bufVal;
  127. buffer.length = bufVal.length; //align the length
  128. for (var i = 0, l = bufVal.length; i < l; i++) {
  129. buffer[i] = bufVal.charAt(i);
  130. }
  131. var newPos = $.inArray("?", buffer);
  132. if (reformatOnly) buffer[newPos] = charAtPos; else buffer.splice(newPos, 1);
  133. if (!needsRefresh && suffixStripped) {
  134. for (var i = 0, l = opts.suffix.length; i < l; i++) {
  135. buffer[buffer.length + i] = opts.suffix.charAt(i);
  136. }
  137. }
  138. return { pos: newPos, "refreshFromBuffer": needsRefresh, "buffer": buffer };
  139. },
  140. onBeforeWrite: function (e, buffer, caretPos, opts) {
  141. if (e && e.type == "blur") {
  142. //handle minvalue
  143. var maskedValue = buffer.join(''),
  144. processValue = maskedValue.replace(opts.prefix, "");
  145. processValue = processValue.replace(opts.suffix, "");
  146. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  147. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  148. if (isFinite(processValue)) {
  149. if (isFinite(opts.min) && parseFloat(processValue) < parseFloat(opts.min)) {
  150. return opts.postFormat((opts.prefix + opts.min).split(''), 0, true, opts);
  151. }
  152. }
  153. var tmpBufSplit = opts.radixPoint != "" ? buffer.join('').split(opts.radixPoint) : [buffer.join('')],
  154. matchRslt = tmpBufSplit[0].match(opts.regex.integerPart(opts)),
  155. matchRsltDigits = tmpBufSplit.length == 2 ? tmpBufSplit[1].match(opts.regex.integerNPart(opts)) : undefined;
  156. if (matchRslt && matchRslt[0] == "-0" && (matchRsltDigits == undefined || matchRsltDigits[0].match(/^0+$/))) {
  157. buffer.splice(matchRslt.index, 1);
  158. }
  159. var radixPosition = $.inArray(opts.radixPoint, buffer);
  160. if (radixPosition != -1 && isFinite(opts.digits) && !opts.digitsOptional) {
  161. for (var i = 1; i <= opts.digits; i++) {
  162. if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == opts.placeholder.charAt(0)) buffer[radixPosition + i] = "0";
  163. }
  164. return { "refreshFromBuffer": true, "buffer": buffer };
  165. }
  166. }
  167. if (opts.autoGroup) {
  168. var rslt = opts.postFormat(buffer, caretPos - 1, true, opts);
  169. rslt.caret = caretPos <= opts.prefix.length ? rslt.pos : rslt.pos + 1;
  170. return rslt;
  171. }
  172. },
  173. regex: {
  174. integerPart: function (opts) { return new RegExp('[' + opts.negationSymbol.front + '\+]?\\d+'); },
  175. integerNPart: function (opts) { return new RegExp('[\\d' + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + ']+'); }
  176. },
  177. signHandler: function (chrs, maskset, pos, strict, opts) {
  178. if (!strict && (opts.allowMinus && chrs === "-") || (opts.allowPlus && chrs === "+")) {
  179. var matchRslt = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  180. if (matchRslt && matchRslt[0].length > 0) {
  181. if (maskset.buffer[matchRslt.index] == (chrs === "-" ? "+" : opts.negationSymbol.front)) {
  182. return { "pos": matchRslt.index, "c": chrs === "-" ? opts.negationSymbol.front : "+", "remove": matchRslt.index, "caret": pos };
  183. } else if (maskset.buffer[matchRslt.index] == (chrs === "-" ? opts.negationSymbol.front : "+")) {
  184. return { "remove": matchRslt.index, "caret": pos - 1 };
  185. } else {
  186. return { "pos": matchRslt.index, "c": chrs === "-" ? opts.negationSymbol.front : "+", "caret": pos + 1 };
  187. }
  188. }
  189. }
  190. return false;
  191. },
  192. radixHandler: function (chrs, maskset, pos, strict, opts) {
  193. if (!strict && chrs === opts.radixPoint && opts.digits > 0) {
  194. var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  195. if (radixPos != -1 && maskset["validPositions"][radixPos]) {
  196. if (maskset["validPositions"][radixPos - 1])
  197. return { "caret": radixPos + 1 };
  198. else return { "pos": integerValue.index, c: integerValue[0], "caret": radixPos + 1 };
  199. } else if (!integerValue || (integerValue["0"] == "0" && (integerValue.index + 1) != pos)) {
  200. maskset.buffer[integerValue ? integerValue.index : pos] = "0";
  201. return { "pos": (integerValue ? integerValue.index : pos) + 1 };
  202. }
  203. }
  204. return false;
  205. },
  206. leadingZeroHandler: function (chrs, maskset, pos, strict, opts) {
  207. var matchRslt = maskset.buffer.join('').match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  208. if (matchRslt && !strict && (radixPosition == -1 || pos <= radixPosition)) {
  209. if (matchRslt["0"].indexOf("0") == 0) {
  210. if (pos < opts.prefix.length) pos = matchRslt.index; //position
  211. var _radixPosition = $.inArray(opts.radixPoint, maskset._buffer);
  212. var digitsMatch = maskset._buffer && maskset.buffer.slice(radixPosition).join('') == maskset._buffer.slice(_radixPosition).join('') || parseInt(maskset.buffer.slice(radixPosition + 1).join('')) == 0;
  213. var integerMatch = maskset._buffer && maskset.buffer.slice(matchRslt.index, radixPosition).join('') == maskset._buffer.slice(opts.prefix.length, _radixPosition).join('') || maskset.buffer.slice(matchRslt.index, radixPosition).join('') == "0";
  214. if (radixPosition == -1 || digitsMatch && integerMatch) {
  215. maskset.buffer.splice(matchRslt.index, 1);
  216. pos = pos > matchRslt.index ? pos - 1 : matchRslt.index;
  217. return { "pos": pos, "remove": matchRslt.index };
  218. } else if (matchRslt.index + 1 == pos || chrs == "0") {
  219. maskset.buffer.splice(matchRslt.index, 1);
  220. pos = matchRslt.index;
  221. return { "pos": pos, "remove": matchRslt.index };
  222. }
  223. } else if (chrs === "0" && pos <= matchRslt.index) {
  224. return false;
  225. }
  226. }
  227. return true;
  228. },
  229. postValidation: function (buffer, opts) {
  230. //handle maxvalue
  231. var isValid = true,
  232. maskedValue = buffer.join(''),
  233. processValue = maskedValue.replace(opts.prefix, "");
  234. processValue = processValue.replace(opts.suffix, "");
  235. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  236. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  237. if (isFinite(processValue)) {
  238. if (isFinite(opts.max)) {
  239. isValid = parseFloat(processValue) <= parseFloat(opts.max);
  240. }
  241. }
  242. return isValid;
  243. },
  244. definitions: {
  245. '~': {
  246. validator: function (chrs, maskset, pos, strict, opts) {
  247. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  248. if (!isValid) {
  249. isValid = opts.radixHandler(chrs, maskset, pos, strict, opts);
  250. if (!isValid) {
  251. isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs);
  252. if (isValid === true) {
  253. isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts);
  254. if (isValid === true) {
  255. //handle overwrite when fixed precision
  256. var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  257. if (opts.digitsOptional === false && pos > radixPosition && !strict) {
  258. isValid = { "pos": pos, "remove": pos };
  259. } else isValid = { pos: pos };
  260. }
  261. }
  262. }
  263. }
  264. return isValid;
  265. },
  266. cardinality: 1,
  267. prevalidator: null
  268. },
  269. '+': {
  270. validator: function (chrs, maskset, pos, strict, opts) {
  271. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  272. if (!isValid && ((strict && opts.allowMinus && chrs === opts.negationSymbol.front) || (opts.allowMinus && chrs == "-") || (opts.allowPlus && chrs == "+"))) {
  273. isValid = true;
  274. }
  275. return isValid;
  276. },
  277. cardinality: 1,
  278. prevalidator: null,
  279. placeholder: ''
  280. },
  281. '-': {
  282. validator: function (chrs, maskset, pos, strict, opts) {
  283. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  284. if (!isValid && strict && opts.allowMinus && chrs === opts.negationSymbol.back) {
  285. isValid = true;
  286. }
  287. return isValid;
  288. },
  289. cardinality: 1,
  290. prevalidator: null,
  291. placeholder: ''
  292. },
  293. ':': {
  294. validator: function (chrs, maskset, pos, strict, opts) {
  295. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  296. if (!isValid) {
  297. var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]";
  298. isValid = new RegExp(radix).test(chrs);
  299. if (isValid && maskset["validPositions"][pos] && maskset["validPositions"][pos]["match"].placeholder == opts.radixPoint) {
  300. isValid = { "caret": pos + 1 };
  301. }
  302. }
  303. return isValid;
  304. },
  305. cardinality: 1,
  306. prevalidator: null,
  307. placeholder: function (opts) { return opts.radixPoint; }
  308. }
  309. },
  310. insertMode: true,
  311. autoUnmask: false,
  312. onUnMask: function (maskedValue, unmaskedValue, opts) {
  313. var processValue = maskedValue.replace(opts.prefix, "");
  314. processValue = processValue.replace(opts.suffix, "");
  315. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  316. //processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  317. return processValue;
  318. },
  319. isComplete: function (buffer, opts) {
  320. var maskedValue = buffer.join(''), bufClone = buffer.slice();
  321. //verify separator positions
  322. opts.postFormat(bufClone, 0, true, opts);
  323. if (bufClone.join('') != maskedValue) return false;
  324. var processValue = maskedValue.replace(opts.prefix, "");
  325. processValue = processValue.replace(opts.suffix, "");
  326. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  327. if (opts.radixPoint === ",") processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  328. return isFinite(processValue);
  329. },
  330. onBeforeMask: function (initialValue, opts) {
  331. if (opts.radixPoint != "" && isFinite(initialValue)) {
  332. initialValue = initialValue.toString().replace(".", opts.radixPoint);
  333. } else {
  334. var kommaMatches = initialValue.match(/,/g);
  335. var dotMatches = initialValue.match(/\./g);
  336. if (dotMatches && kommaMatches) {
  337. if (dotMatches.length > kommaMatches.length) {
  338. initialValue = initialValue.replace(/\./g, "");
  339. initialValue = initialValue.replace(",", opts.radixPoint);
  340. } else if (kommaMatches.length > dotMatches.length) {
  341. initialValue = initialValue.replace(/,/g, "");
  342. initialValue = initialValue.replace(".", opts.radixPoint);
  343. } else { //equal
  344. initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "");
  345. }
  346. } else {
  347. initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  348. }
  349. }
  350. if (opts.digits == 0) {
  351. if (initialValue.indexOf(".") != -1) {
  352. initialValue = initialValue.substring(0, initialValue.indexOf("."));
  353. } else if (initialValue.indexOf(",") != -1) {
  354. initialValue = initialValue.substring(0, initialValue.indexOf(","));
  355. }
  356. }
  357. return initialValue;
  358. },
  359. canClearPosition: function (maskset, position, lvp, strict, opts) {
  360. var positionInput = maskset["validPositions"][position].input,
  361. canClear = (positionInput != opts.radixPoint && isFinite(positionInput)) ||
  362. position == lvp ||
  363. positionInput == opts.groupSeparator ||
  364. positionInput == opts.negationSymbol.front ||
  365. positionInput == opts.negationSymbol.back,
  366. posOffset = 0;
  367. if (canClear && isFinite(positionInput)) {
  368. var matchRslt = maskset["buffer"].join('').substr(0, position).match(opts.regex.integerNPart(opts));
  369. if (!strict) {
  370. var pos = position + 1, isNull = matchRslt == null || parseInt(matchRslt["0"].replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "")) == 0;
  371. if (isNull) {
  372. while (maskset["validPositions"][pos] && (maskset["validPositions"][pos].input == opts.groupSeparator || maskset["validPositions"][pos].input == "0")) {
  373. delete maskset["validPositions"][pos];
  374. pos++;
  375. }
  376. }
  377. }
  378. var buffer = [];
  379. //build new buffer from validPositions
  380. for (var vp in maskset.validPositions) {
  381. buffer.push(maskset.validPositions[vp].input);
  382. }
  383. matchRslt = buffer.join('').match(opts.regex.integerNPart(opts));
  384. var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  385. if (matchRslt && (radixPosition == -1 || position <= radixPosition)) {
  386. if (matchRslt["0"].indexOf("0") == 0) {
  387. canClear = matchRslt.index != position || radixPosition == -1;
  388. } else {
  389. var intPart = parseInt(matchRslt["0"].replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""));
  390. if (radixPosition != -1 && intPart < 10 && opts.placeholder.charAt(0) == "0") {
  391. maskset["validPositions"][position].input = "0";
  392. maskset["p"] = opts.prefix.length + 1;
  393. canClear = false;
  394. }
  395. }
  396. }
  397. }
  398. return canClear;
  399. }
  400. },
  401. 'currency': {
  402. prefix: "$ ",
  403. groupSeparator: ",",
  404. alias: "numeric",
  405. placeholder: "0",
  406. autoGroup: true,
  407. digits: 2,
  408. digitsOptional: false,
  409. clearMaskOnLostFocus: false
  410. },
  411. 'decimal': {
  412. alias: "numeric"
  413. },
  414. 'integer': {
  415. alias: "numeric",
  416. digits: "0",
  417. radixPoint: ""
  418. }
  419. });
  420. return $.fn.inputmask;
  421. })(jQuery);