jquery.inputmask.numeric.extensions.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. //position overflow corrections
  84. pos = pos >= buffer.length ? buffer.length - 1 : (pos < opts.prefix.length ? opts.prefix.length : pos);
  85. var needsRefresh = false, charAtPos = buffer[pos];
  86. if (opts.groupSeparator == "" ||
  87. ($.inArray(opts.radixPoint, buffer) != -1 && pos >= $.inArray(opts.radixPoint, buffer)) ||
  88. new RegExp('[-\+]').test(charAtPos)
  89. )
  90. return { pos: pos };
  91. var cbuf = buffer.slice();
  92. if (charAtPos == opts.groupSeparator) {
  93. cbuf.splice(pos--, 1);
  94. charAtPos = cbuf[pos];
  95. }
  96. if (reformatOnly) cbuf[pos] = "?"; else cbuf.splice(pos, 0, "?"); //set position indicator
  97. var bufVal = cbuf.join(''), bufValOrigin = bufVal;
  98. if (bufVal.length > 0 && opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
  99. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  100. needsRefresh = bufVal.indexOf(opts.groupSeparator) == 0;
  101. bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
  102. var radixSplit = bufVal.split(opts.radixPoint);
  103. bufVal = opts.radixPoint == "" ? bufVal : radixSplit[0];
  104. if (bufVal != (opts.prefix + "?0") && bufVal.length >= (opts.groupSize + opts.prefix.length)) {
  105. //needsRefresh = true;
  106. var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
  107. while (reg.test(bufVal)) {
  108. bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
  109. bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
  110. }
  111. }
  112. if (opts.radixPoint != "" && radixSplit.length > 1)
  113. bufVal += opts.radixPoint + radixSplit[1];
  114. }
  115. needsRefresh = bufValOrigin != bufVal;
  116. buffer.length = bufVal.length; //align the length
  117. for (var i = 0, l = bufVal.length; i < l; i++) {
  118. buffer[i] = bufVal.charAt(i);
  119. }
  120. var newPos = $.inArray("?", buffer);
  121. if (reformatOnly) buffer[newPos] = charAtPos; else buffer.splice(newPos, 1);
  122. return { pos: newPos, "refreshFromBuffer": needsRefresh, "buffer": buffer };
  123. },
  124. onBeforeWrite: function (e, buffer, caretPos, opts) {
  125. if (e && e.type == "blur") {
  126. //handle minvalue
  127. var maskedValue = buffer.join(''),
  128. processValue = maskedValue.replace(opts.prefix, "");
  129. processValue = processValue.replace(opts.suffix, "");
  130. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  131. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  132. if (isFinite(processValue)) {
  133. if (isFinite(opts.min) && parseFloat(processValue) < parseFloat(opts.min)) {
  134. return opts.postFormat((opts.prefix + opts.min).split(''), 0, true, opts);
  135. }
  136. }
  137. var tmpBufSplit = opts.radixPoint != "" ? buffer.join('').split(opts.radixPoint) : [buffer.join('')],
  138. matchRslt = tmpBufSplit[0].match(opts.regex.integerPart(opts)),
  139. matchRsltDigits = tmpBufSplit.length == 2 ? tmpBufSplit[1].match(opts.regex.integerNPart(opts)) : undefined;
  140. if (matchRslt && matchRslt[0] == "-0" && (matchRsltDigits == undefined || matchRsltDigits[0].match(/^0+$/))) {
  141. buffer.splice(matchRslt.index, 1);
  142. }
  143. var radixPosition = $.inArray(opts.radixPoint, buffer);
  144. if (radixPosition != -1 && isFinite(opts.digits) && !opts.digitsOptional) {
  145. for (var i = 1; i <= opts.digits; i++) {
  146. if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == opts.placeholder.charAt(0)) buffer[radixPosition + i] = "0";
  147. }
  148. return { "refreshFromBuffer": true, "buffer": buffer };
  149. }
  150. }
  151. if (opts.autoGroup) {
  152. var rslt = opts.postFormat(buffer, caretPos - 1, true, opts);
  153. rslt.caret = caretPos == 0 ? caretPos : rslt.pos + 1;
  154. return rslt;
  155. }
  156. },
  157. regex: {
  158. integerPart: function (opts) { return new RegExp('[' + opts.negationSymbol.front + '\+]?\\d+'); },
  159. integerNPart: function (opts) { return new RegExp('[\\d' + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + ']+'); }
  160. },
  161. signHandler: function (chrs, maskset, pos, strict, opts) {
  162. if (!strict && (opts.allowMinus && chrs === "-") || (opts.allowPlus && chrs === "+")) {
  163. var matchRslt = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  164. if (matchRslt && matchRslt[0].length > 0) {
  165. if (maskset.buffer[matchRslt.index] == (chrs === "-" ? "+" : opts.negationSymbol.front)) {
  166. return { "pos": matchRslt.index, "c": chrs === "-" ? opts.negationSymbol.front : "+", "remove": matchRslt.index, "caret": pos };
  167. } else if (maskset.buffer[matchRslt.index] == (chrs === "-" ? opts.negationSymbol.front : "+")) {
  168. return { "remove": matchRslt.index, "caret": pos - 1 };
  169. } else {
  170. return { "pos": matchRslt.index, "c": chrs === "-" ? opts.negationSymbol.front : "+", "caret": pos + 1 };
  171. }
  172. }
  173. }
  174. return false;
  175. },
  176. radixHandler: function (chrs, maskset, pos, strict, opts) {
  177. if (!strict && chrs === opts.radixPoint && opts.digits > 0) {
  178. var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  179. if (radixPos != -1 && maskset["validPositions"][radixPos]) {
  180. if (maskset["validPositions"][radixPos - 1])
  181. return { "caret": radixPos + 1 };
  182. else return { "pos": integerValue.index, c: integerValue[0], "caret": radixPos + 1 };
  183. } else if (!integerValue || (integerValue["0"] == "0" && (integerValue.index + 1) != pos)) {
  184. maskset.buffer[integerValue ? integerValue.index : pos] = "0";
  185. return { "pos": (integerValue ? integerValue.index : pos) + 1 };
  186. }
  187. }
  188. return false;
  189. },
  190. leadingZeroHandler: function (chrs, maskset, pos, strict, opts) {
  191. var matchRslt = maskset.buffer.join('').match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  192. if (matchRslt && !strict && (radixPosition == -1 || pos <= radixPosition)) {
  193. if (matchRslt["0"].indexOf("0") == 0) {
  194. if (pos < opts.prefix.length) pos = matchRslt.index; //position
  195. var _radixPosition = $.inArray(opts.radixPoint, maskset._buffer);
  196. var digitsMatch = maskset._buffer && maskset.buffer.slice(radixPosition).join('') == maskset._buffer.slice(_radixPosition).join('') || parseInt(maskset.buffer.slice(radixPosition + 1).join('')) == 0;
  197. 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";
  198. if (radixPosition == -1 || digitsMatch && integerMatch) {
  199. maskset.buffer.splice(matchRslt.index, 1);
  200. pos = pos > matchRslt.index ? pos - 1 : matchRslt.index;
  201. return { "pos": pos, "remove": matchRslt.index };
  202. } else if (matchRslt.index + 1 == pos || chrs == "0") {
  203. maskset.buffer.splice(matchRslt.index, 1);
  204. pos = matchRslt.index;
  205. return { "pos": pos, "remove": matchRslt.index };
  206. }
  207. } else if (chrs === "0" && pos <= matchRslt.index) {
  208. return false;
  209. }
  210. }
  211. return true;
  212. },
  213. postValidation: function (buffer, opts) {
  214. //handle maxvalue
  215. var isValid = true,
  216. maskedValue = buffer.join(''),
  217. processValue = maskedValue.replace(opts.prefix, "");
  218. processValue = processValue.replace(opts.suffix, "");
  219. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  220. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  221. if (isFinite(processValue)) {
  222. if (isFinite(opts.max)) {
  223. isValid = parseFloat(processValue) <= parseFloat(opts.max);
  224. }
  225. }
  226. return isValid;
  227. },
  228. definitions: {
  229. '~': {
  230. validator: function (chrs, maskset, pos, strict, opts) {
  231. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  232. if (!isValid) {
  233. isValid = opts.radixHandler(chrs, maskset, pos, strict, opts);
  234. if (!isValid) {
  235. isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs);
  236. if (isValid === true) {
  237. isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts);
  238. if (isValid === true) {
  239. //handle overwrite when fixed precision
  240. var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  241. if (opts.digitsOptional === false && pos > radixPosition && !strict) {
  242. isValid = { "pos": pos, "remove": pos };
  243. } else isValid = { pos: pos };
  244. }
  245. }
  246. }
  247. }
  248. return isValid;
  249. },
  250. cardinality: 1,
  251. prevalidator: null
  252. },
  253. '+': {
  254. validator: function (chrs, maskset, pos, strict, opts) {
  255. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  256. if (!isValid && ((strict && opts.allowMinus && chrs === opts.negationSymbol.front) || (opts.allowMinus && chrs == "-") || (opts.allowPlus && chrs == "+"))) {
  257. isValid = true;
  258. }
  259. return isValid;
  260. },
  261. cardinality: 1,
  262. prevalidator: null,
  263. placeholder: ''
  264. },
  265. '-': {
  266. validator: function (chrs, maskset, pos, strict, opts) {
  267. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  268. if (!isValid && strict && opts.allowMinus && chrs === opts.negationSymbol.back) {
  269. isValid = true;
  270. }
  271. return isValid;
  272. },
  273. cardinality: 1,
  274. prevalidator: null,
  275. placeholder: ''
  276. },
  277. ':': {
  278. validator: function (chrs, maskset, pos, strict, opts) {
  279. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  280. if (!isValid) {
  281. var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]";
  282. isValid = new RegExp(radix).test(chrs);
  283. if (isValid && maskset["validPositions"][pos] && maskset["validPositions"][pos]["match"].placeholder == opts.radixPoint) {
  284. isValid = { "caret": pos + 1 };
  285. }
  286. }
  287. return isValid;
  288. },
  289. cardinality: 1,
  290. prevalidator: null,
  291. placeholder: function (opts) { return opts.radixPoint; }
  292. }
  293. },
  294. insertMode: true,
  295. autoUnmask: false,
  296. onUnMask: function (maskedValue, unmaskedValue, opts) {
  297. var processValue = maskedValue.replace(opts.prefix, "");
  298. processValue = processValue.replace(opts.suffix, "");
  299. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  300. //processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  301. return processValue;
  302. },
  303. isComplete: function (buffer, opts) {
  304. var maskedValue = buffer.join(''), bufClone = buffer.slice();
  305. //verify separator positions
  306. opts.postFormat(bufClone, 0, true, opts);
  307. if (bufClone.join('') != maskedValue) return false;
  308. var processValue = maskedValue.replace(opts.prefix, "");
  309. processValue = processValue.replace(opts.suffix, "");
  310. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  311. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  312. return isFinite(processValue);
  313. },
  314. onBeforeMask: function (initialValue, opts) {
  315. if (opts.radixPoint != "" && isFinite(initialValue)) {
  316. initialValue = initialValue.toString().replace(".", opts.radixPoint);
  317. } else {
  318. var kommaMatches = initialValue.match(/,/g);
  319. var dotMatches = initialValue.match(/\./g);
  320. if (dotMatches && kommaMatches) {
  321. if (dotMatches.length > kommaMatches.length) {
  322. initialValue = initialValue.replace(/\./g, "");
  323. initialValue = initialValue.replace(",", opts.radixPoint);
  324. } else if (kommaMatches.length > dotMatches.length) {
  325. initialValue = initialValue.replace(/,/g, "");
  326. initialValue = initialValue.replace(".", opts.radixPoint);
  327. } else { //equal
  328. initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "");
  329. }
  330. } else {
  331. initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  332. }
  333. }
  334. if (opts.digits == 0) {
  335. if (initialValue.indexOf(".") != -1) {
  336. initialValue = initialValue.substring(0, initialValue.indexOf("."));
  337. } else if (initialValue.indexOf(",") != -1) {
  338. initialValue = initialValue.substring(0, initialValue.indexOf(","));
  339. }
  340. }
  341. return initialValue;
  342. },
  343. canClearPosition: function (maskset, position, lvp, strict, opts) {
  344. var positionInput = maskset["validPositions"][position].input,
  345. canClear = (positionInput != opts.radixPoint && isFinite(positionInput)) || position == lvp || positionInput == opts.groupSeparator,
  346. posOffset = 0;
  347. if (canClear && isFinite(positionInput)) {
  348. var matchRslt = maskset["buffer"].join('').substr(0, position).match(opts.regex.integerNPart(opts));
  349. if (!strict) {
  350. var pos = position + 1, isNull = matchRslt == null || parseInt(matchRslt["0"].replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "")) == 0;
  351. if (isNull) {
  352. while (maskset["validPositions"][pos] && (maskset["validPositions"][pos].input == opts.groupSeparator || maskset["validPositions"][pos].input == "0")) {
  353. delete maskset["validPositions"][pos];
  354. pos++;
  355. }
  356. }
  357. }
  358. var buffer = [];
  359. //build new buffer from validPositions
  360. for (var vp in maskset.validPositions) {
  361. buffer.push(maskset.validPositions[vp].input);
  362. }
  363. matchRslt = buffer.join('').match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  364. if (matchRslt && (radixPosition == -1 || position <= radixPosition)) {
  365. if (matchRslt["0"].indexOf("0") == 0) {
  366. canClear = matchRslt.index != position || radixPosition == -1;
  367. } else {
  368. var intPart = parseInt(matchRslt["0"].replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""));
  369. if (radixPosition != -1 && intPart < 10 && opts.placeholder.charAt(0) == "0") {
  370. maskset["validPositions"][position].input = "0";
  371. maskset["p"] = opts.prefix.length + 1;
  372. canClear = false;
  373. }
  374. }
  375. }
  376. }
  377. return canClear;
  378. }
  379. },
  380. 'currency': {
  381. prefix: "$ ",
  382. groupSeparator: ",",
  383. alias: "numeric",
  384. placeholder: "0",
  385. autoGroup: true,
  386. digits: 2,
  387. digitsOptional: false,
  388. clearMaskOnLostFocus: false
  389. },
  390. 'decimal': {
  391. alias: "numeric"
  392. },
  393. 'integer': {
  394. alias: "numeric",
  395. digits: "0",
  396. radixPoint: ""
  397. }
  398. });
  399. return $.fn.inputmask;
  400. })(jQuery);