jquery.inputmask.numeric.extensions.js 22 KB

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