簡體   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