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



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

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

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

  3. 十进制 (.( 在文本框中只能出现一次。

我刚才根据你的条件写了这个,在下面测试一下:

更新:修改为在jquery和javascript内联中工作

// 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>

编辑:我想这就是你要找的。在 jsfiddle.net 中找到了这一点。无需插件。

.HTML:

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

爪哇语

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;

};

最新更新