首页 > 解决方案 > 如何使用 Jquery 在输入文本框中验证允许减号(-)和仅数字?

问题描述

如何在金额输入字段中进行验证?

  1. 在文本框中只允许减号(负号)一次。例如,-10.00。不允许使用其他特殊字符,因为它是一个金额字段。

  2. 它不应该允许字母。只允许数字。

  3. Decimal(.) 在文本框中只能出现一次。

标签: javascriptjquery

解决方案


我刚才是根据你的情况写的,下面测试一下:

更新: 修改为适用于 jquery 和 javascript inline

// This is a middleware that takes as parameter "decimals" which is by default 2

currencyNumber = function(decimals) {

  if (typeof decimals !== 'number') {
    decimals = 2;
  }

  return function(e) {

    var input = $(this instanceof Window ? e : e.currentTarget);

    var value = $.trim(input.val());

    var hasNegativeNumber = value.substr(0, 1) === '-' ? '-' : '';

    var nextValue = value
      .replace(/\.+/g, '.')
      .replace(/[^0-9\.]+/g, '');

    if (nextValue === '.' || (nextValue.length > 1 && nextValue === "00")) {
      nextValue = '';
    }

    var dotsFound = nextValue.split('.').filter(function(i) {
      return i.length;
    });
    var afterDot = '';
    var beforeDot = '';

    if (dotsFound.length > 1) {

      beforeDot = dotsFound[0];

      dotsFound.splice(0, 1);

      afterDot = dotsFound.join('');

      nextValue = +(beforeDot) + '.' + afterDot.substr(0, decimals);

    }

    if (nextValue.substr(nextValue.length - 1, 1) === '.') {

      input.one('change', function() {

        if (nextValue.substr(nextValue.length - 1, 1) === '.') {
          nextValue = nextValue.substr(0, nextValue.length - 1);

          input.val(hasNegativeNumber + nextValue);

        }

        $(this).off('change');

      })

    } else {

      input.off('change')

    }

    input.val(hasNegativeNumber + nextValue);

  };


}

// Here is where you call the middleware

$("#amount").on("keyup", currencyNumber(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  Test your number (bind is from jquery):
  <input id="amount" type='text' />
  <br /> Test your number (bind is from javascript inline):
  <input id="amount-inline" onkeyup="currencyNumber(3)(this);" type='text' />

</div>


推荐阅读