jquery.inputmask.numeric.extensions.js 20 KB

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