common-js.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <script>
  2. /**
  3. * 数字验证
  4. * @param val
  5. * @param type
  6. * @param decimalNum
  7. * @param title
  8. * @returns {*}
  9. */
  10. function numberHandle(val, type = 1, decimalNum = 0, title = '') {
  11. val += '';
  12. let dataValue = '';
  13. //正则类型
  14. switch (type) {
  15. case 1://只能输入正整数正则(不包括小数)
  16. dataValue = val.replace(/[^0-9]/ig, "");
  17. break;
  18. case 2://只能输入正数正则(包括小数)
  19. dataValue = val.replace(/[^\d\.]{1}/g, "");
  20. dataValue = this.decimalFiltersHandle(dataValue, decimalNum, title);
  21. break;
  22. default:
  23. dataValue = val;
  24. }
  25. //去除数字前面的0,例子:0123处理后为123
  26. if (dataValue.length >= 2 && dataValue.substring(0, 1) == 0 && dataValue.substring(1, 2) !== '.') {
  27. dataValue = dataValue.replace(/^0+/g, "");
  28. if (dataValue == '') {
  29. dataValue = '0';
  30. }
  31. }
  32. return dataValue;
  33. }
  34. function decimalFiltersHandle(data, num = 0, title) {
  35. //当前输入为空或第一位字符输入小数点的直接返回空
  36. if (data === '' || data === '.') {
  37. return '';
  38. }
  39. //当前没有小数点的时候不需要处理小数,直接返回
  40. if (data.indexOf(".") === -1) {
  41. return data;
  42. }
  43. let originData = data;
  44. // 获取用户输入内容,提取数字
  45. let input = data.match(/[0-9]+/g);
  46. // 判断用户输入.x or x.x
  47. let posDecimal = originData.toString().indexOf(".");
  48. if (posDecimal === 0) {
  49. input.splice(0, 0, "0.");
  50. } else {
  51. input.splice(1, 0, ".");
  52. }
  53. //处理后的小数值
  54. input = input.toString().replaceAll(",", "");
  55. //判断是否需要保留几位小数点
  56. var y = String(input).indexOf(".") + 1;//获取小数点的位置
  57. var count = String(input).length - y;//获取小数点后的个数
  58. if (count > 0 && count > num) {
  59. input = input.substring(0, input.length - 1);
  60. let msg = title + "只能输入" + num + "位小数";
  61. if (num === 0) {
  62. msg = title + "只能是整数";
  63. }
  64. Vue.prototype.$message.error(msg);
  65. }
  66. return input;
  67. }
  68. </script>