數值使用小數點最多2個小數點驗證。 依賴關係jQuery。
HTML -
<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point) </div>
jQuery代碼 -
方法1
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
var matchedString = $(this).val().match(patt);
if (matchedString) {
$(this).val(matchedString);
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
方法2 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/(?<=\.\d\d).+/i);
$(this).val($(this).val().replace(patt, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
的功能不爲我工作很好。我可以輸入122.33.33.3343。 – laaposto
嗨laaposto,你有沒有嘗試從按鍵功能調用它? $( '#量')按鍵(功能(事件){\t \t \t \t \t \t \t \t \t \t \t \t checkForInvalidCharacters(事件,$(本)); \t \t \t \t \t}); – user676567