jquery.inputmask.numeric.extensions.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. opts.definitions[";"] = opts.definitions["~"]; //clone integer def for decimals
  45. var mask = autoEscape(opts.prefix);
  46. mask += "[+]";
  47. mask += "~{1," + opts.integerDigits + "}";
  48. if (opts.digits != undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) {
  49. if (opts.digitsOptional)
  50. mask += "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]";
  51. else mask += (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}";
  52. }
  53. mask += autoEscape(opts.suffix);
  54. opts.greedy = false; //enforce greedy false
  55. return mask;
  56. },
  57. placeholder: "",
  58. greedy: false,
  59. digits: "*", //number of fractionalDigits
  60. digitsOptional: true,
  61. groupSeparator: "",//",", // | "."
  62. radixPoint: ".",
  63. radixFocus: true,
  64. groupSize: 3,
  65. autoGroup: false,
  66. allowPlus: true,
  67. allowMinus: true,
  68. integerDigits: "+", //number of integerDigits
  69. prefix: "",
  70. suffix: "",
  71. rightAlign: true,
  72. decimalProtect: true, //do not allow assumption of decimals input without entering the radixpoint
  73. postFormat: function (buffer, pos, reformatOnly, opts) { //this needs to be removed // this is crap
  74. //position overflow corrections
  75. pos = pos >= buffer.length ? buffer.length - 1 : (pos < opts.prefix.length ? opts.prefix.length : pos);
  76. var needsRefresh = false, charAtPos = buffer[pos];
  77. if (opts.groupSeparator == "" ||
  78. ($.inArray(opts.radixPoint, buffer) != -1 && pos >= $.inArray(opts.radixPoint, buffer)) ||
  79. new RegExp('[-\+]').test(charAtPos)
  80. )
  81. return { pos: pos };
  82. var cbuf = buffer.slice();
  83. if (charAtPos == opts.groupSeparator) {
  84. cbuf.splice(pos--, 1);
  85. charAtPos = cbuf[pos];
  86. }
  87. if (reformatOnly) cbuf[pos] = "?"; else cbuf.splice(pos, 0, "?"); //set position indicator
  88. var bufVal = cbuf.join(''), bufValOrigin = bufVal;
  89. if (bufVal.length > 0 && opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
  90. var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
  91. needsRefresh = bufVal.indexOf(opts.groupSeparator) == 0;
  92. bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
  93. var radixSplit = bufVal.split(opts.radixPoint);
  94. bufVal = opts.radixPoint == "" ? bufVal : radixSplit[0];
  95. if (bufVal != (opts.prefix + "?0") && bufVal.length >= (opts.groupSize + opts.prefix.length)) {
  96. //needsRefresh = true;
  97. var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
  98. while (reg.test(bufVal)) {
  99. bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
  100. bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
  101. }
  102. }
  103. if (opts.radixPoint != "" && radixSplit.length > 1)
  104. bufVal += opts.radixPoint + radixSplit[1];
  105. }
  106. needsRefresh = bufValOrigin != bufVal;
  107. buffer.length = bufVal.length; //align the length
  108. for (var i = 0, l = bufVal.length; i < l; i++) {
  109. buffer[i] = bufVal.charAt(i);
  110. }
  111. var newPos = $.inArray("?", buffer);
  112. if (reformatOnly) buffer[newPos] = charAtPos; else buffer.splice(newPos, 1);
  113. return { pos: newPos, "refreshFromBuffer": needsRefresh };
  114. },
  115. onBeforeWrite: function (e, buffer, caretPos, opts) {
  116. if (e && e.type == "blur") {
  117. var tmpBufSplit = opts.radixPoint != "" ? buffer.join('').split(opts.radixPoint) : [buffer.join('')],
  118. matchRslt = tmpBufSplit[0].match(opts.regex.integerPart(opts)),
  119. matchRsltDigits = tmpBufSplit.length == 2 ? tmpBufSplit[1].match(opts.regex.integerNPart(opts)) : undefined;
  120. if (matchRslt && matchRslt[0] == "-0" && (matchRsltDigits == undefined || matchRsltDigits[0].match(/^0+$/))) {
  121. buffer.splice(matchRslt.index, 1);
  122. }
  123. var radixPosition = $.inArray(opts.radixPoint, buffer);
  124. if (radixPosition != -1 && isFinite(opts.digits) && !opts.digitsOptional) {
  125. for (var i = 1; i <= opts.digits; i++) {
  126. if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == opts.placeholder.charAt(0)) buffer[radixPosition + i] = "0";
  127. }
  128. return { "refreshFromBuffer": true, "buffer": buffer };
  129. }
  130. }
  131. if (opts.autoGroup) {
  132. var rslt = opts.postFormat(buffer, caretPos - 1, true, opts);
  133. rslt.caret = rslt.pos + 1;
  134. return rslt;
  135. }
  136. },
  137. regex: {
  138. integerPart: function (opts) { return new RegExp('[-\+]?\\d+'); },
  139. integerNPart: function (opts) { return new RegExp('[\\d' + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + ']+'); }
  140. },
  141. signHandler: function (chrs, maskset, pos, strict, opts) {
  142. if (!strict && (opts.allowMinus && chrs === "-" || opts.allowPlus && chrs === "+")) {
  143. var matchRslt = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  144. if (matchRslt && matchRslt[0].length > 0) {
  145. if (maskset.buffer[matchRslt.index] == (chrs === "-" ? "+" : "-")) {
  146. return { "pos": matchRslt.index, "c": chrs, "remove": matchRslt.index, "caret": pos };
  147. } else if (maskset.buffer[matchRslt.index] == (chrs === "-" ? "-" : "+")) {
  148. return { "remove": matchRslt.index, "caret": pos - 1 };
  149. } else {
  150. return { "pos": matchRslt.index, "c": chrs, "caret": pos + 1 };
  151. }
  152. }
  153. }
  154. return false;
  155. },
  156. radixHandler: function (chrs, maskset, pos, strict, opts) {
  157. if (!strict && chrs === opts.radixPoint && opts.digits > 0) {
  158. var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join('').match(opts.regex.integerPart(opts));
  159. if (radixPos != -1 && maskset["validPositions"][radixPos]) {
  160. if (maskset["validPositions"][radixPos - 1])
  161. return { "caret": radixPos + 1 };
  162. else return { "pos": integerValue.index, c: integerValue[0], "caret": radixPos + 1 };
  163. } else if (!integerValue || (integerValue["0"] == "0" && (integerValue.index + 1) != pos)) {
  164. maskset.buffer[integerValue ? integerValue.index : pos] = "0";
  165. return { "pos": (integerValue ? integerValue.index : pos) + 1 };
  166. }
  167. }
  168. return false;
  169. },
  170. leadingZeroHandler: function (chrs, maskset, pos, strict, opts) {
  171. var matchRslt = maskset.buffer.join('').match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  172. if (matchRslt && !strict && (radixPosition == -1 || pos <= radixPosition)) {
  173. if (matchRslt["0"].indexOf("0") == 0) {
  174. if (pos < opts.prefix.length) pos = matchRslt.index; //position
  175. var _radixPosition = $.inArray(opts.radixPoint, maskset._buffer);
  176. var digitsMatch = maskset._buffer && maskset.buffer.slice(radixPosition).join('') == maskset._buffer.slice(_radixPosition).join('');
  177. var integerMatch = maskset._buffer && maskset.buffer.slice(matchRslt.index, radixPosition).join('') == maskset._buffer.slice(opts.prefix.length, _radixPosition).join('');
  178. if (radixPosition == -1 || digitsMatch && integerMatch) {
  179. maskset.buffer.splice(matchRslt.index, 1);
  180. pos = pos > matchRslt.index ? pos - 1 : matchRslt.index;
  181. return { "pos": pos, "remove": matchRslt.index };
  182. } else if (matchRslt.index + 1 == pos || chrs == "0") {
  183. maskset.buffer.splice(matchRslt.index, 1);
  184. pos = matchRslt.index;
  185. return { "pos": pos, "remove": matchRslt.index };
  186. }
  187. } else if (chrs === "0" && pos <= matchRslt.index) {
  188. return false;
  189. }
  190. }
  191. return true;
  192. },
  193. definitions: {
  194. '~': {
  195. validator: function (chrs, maskset, pos, strict, opts) {
  196. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  197. if (!isValid) {
  198. isValid = opts.radixHandler(chrs, maskset, pos, strict, opts);
  199. if (!isValid) {
  200. isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs);
  201. if (isValid === true) {
  202. isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts);
  203. if (isValid === true) {
  204. //handle overwrite when fixed precision
  205. var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  206. if (opts.digitsOptional === false && pos > radixPosition && !strict) {
  207. isValid = { "pos": pos, "remove": pos };
  208. } else isValid = { pos: pos };
  209. }
  210. }
  211. }
  212. }
  213. return isValid;
  214. },
  215. cardinality: 1,
  216. prevalidator: null
  217. },
  218. '+': {
  219. validator: function (chrs, maskset, pos, strict, opts) {
  220. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  221. if (!isValid) {
  222. isValid = (opts.allowMinus && chrs == "-") || (opts.allowPlus && chrs == "+");
  223. }
  224. return isValid;
  225. },
  226. cardinality: 1,
  227. prevalidator: null,
  228. placeholder: ''
  229. },
  230. ':': {
  231. validator: function (chrs, maskset, pos, strict, opts) {
  232. var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
  233. if (!isValid) {
  234. var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]";
  235. isValid = new RegExp(radix).test(chrs);
  236. if (isValid && maskset["validPositions"][pos] && maskset["validPositions"][pos]["match"].placeholder == opts.radixPoint) {
  237. isValid = { "caret": pos + 1 };
  238. }
  239. }
  240. return isValid;
  241. },
  242. cardinality: 1,
  243. prevalidator: null,
  244. placeholder: function (opts) { return opts.radixPoint; }
  245. }
  246. },
  247. insertMode: true,
  248. autoUnmask: false,
  249. onUnMask: function (maskedValue, unmaskedValue, opts) {
  250. var processValue = maskedValue.replace(opts.prefix, "");
  251. processValue = processValue.replace(opts.suffix, "");
  252. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  253. //processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  254. return processValue;
  255. },
  256. isComplete: function (buffer, opts) {
  257. var maskedValue = buffer.join(''), bufClone = buffer.slice();
  258. //verify separator positions
  259. opts.postFormat(bufClone, 0, true, opts);
  260. if (bufClone.join('') != maskedValue) return false;
  261. var processValue = maskedValue.replace(opts.prefix, "");
  262. processValue = processValue.replace(opts.suffix, "");
  263. processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  264. processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
  265. return isFinite(processValue);
  266. },
  267. onBeforeMask: function (initialValue, opts) {
  268. if (opts.radixPoint != "" && isFinite(initialValue)) {
  269. initialValue = initialValue.toString().replace(".", opts.radixPoint);
  270. } else {
  271. var kommaMatches = initialValue.match(/,/g);
  272. var dotMatches = initialValue.match(/\./g);
  273. if (dotMatches && kommaMatches) {
  274. if (dotMatches.length > kommaMatches.length) {
  275. initialValue = initialValue.replace(/\./g, "");
  276. initialValue = initialValue.replace(",", opts.radixPoint);
  277. } else if (kommaMatches.length > dotMatches.length) {
  278. initialValue = initialValue.replace(/,/g, "");
  279. initialValue = initialValue.replace(".", opts.radixPoint);
  280. } else { //equal
  281. initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "");
  282. }
  283. } else {
  284. initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
  285. }
  286. }
  287. if (opts.digits == 0) {
  288. if (initialValue.indexOf(".") != -1) {
  289. initialValue = initialValue.substring(0, initialValue.indexOf("."));
  290. } else if (initialValue.indexOf(",") != -1) {
  291. initialValue = initialValue.substring(0, initialValue.indexOf(","));
  292. }
  293. }
  294. return initialValue;
  295. },
  296. canClearPosition: function (maskset, position, lvp, opts) {
  297. var positionInput = maskset["validPositions"][position].input, canClear = (positionInput != opts.radixPoint && isFinite(positionInput)) || position == lvp,
  298. posOffset = 0;
  299. if (canClear && isFinite(positionInput)) {
  300. var pos = position + 1;
  301. while (maskset["validPositions"][pos] && (maskset["validPositions"][pos].input == opts.groupSeparator || maskset["validPositions"][pos].input == "0")) {
  302. delete maskset["validPositions"][pos];
  303. pos++;
  304. }
  305. var buffer = [];
  306. //build new buffer from validPositions
  307. for (var vp in maskset.validPositions) {
  308. buffer.push(maskset.validPositions[vp].input);
  309. }
  310. var matchRslt = buffer.join('').match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
  311. if (matchRslt && (radixPosition == -1 || position <= radixPosition)) {
  312. if (matchRslt["0"].indexOf("0") == 0) {
  313. canClear = matchRslt.index != position || radixPosition == -1;
  314. } else {
  315. var intPart = parseInt(matchRslt["0"].replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""));
  316. if (radixPosition != -1 && intPart < 10) {
  317. maskset["validPositions"][position].input = "0";
  318. canClear = false;
  319. }
  320. }
  321. }
  322. }
  323. return canClear;
  324. }
  325. },
  326. 'currency': {
  327. prefix: "$ ",
  328. groupSeparator: ",",
  329. alias: "numeric",
  330. placeholder: "0",
  331. autoGroup: true,
  332. digits: 2,
  333. digitsOptional: false,
  334. clearMaskOnLostFocus: false
  335. },
  336. 'decimal': {
  337. alias: "numeric"
  338. },
  339. 'integer': {
  340. alias: "numeric",
  341. digits: "0",
  342. radixPoint: ""
  343. }
  344. });
  345. return $.fn.inputmask;
  346. })(jQuery);