繁体   English   中英

如何使用Jquery验证输入文本框中的允许减号(-)和仅数字?

[英]How to validate allow minus(-) and only numbers in input textbox using Jquery?

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

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

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

  3. 在文本框中,Decimal(。)应该只能是一次。

编辑:我想这就是您要寻找的。 jsfiddle.net找到了这个。 无需插件。

HTML:

<input type="text" maxlength="10" id="myInput">

Java脚本

var input = document.getElementById("myInput");

input.onkeypress = function(e) {    e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
    return;
}

var typedChar = String.fromCharCode(charCode);

// Allow numeric characters
if (/\d/.test(typedChar)) {
    return;
}

// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
    return;
}

// In all other cases, suppress the event
return false;

};

我刚刚根据您的条件编写了此代码,请在下面进行测试:

更新:修改为可同时在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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM