[英]How to prevent user from entering decimals?
我的網站上有一個訂單頁面。 某些訂單商品可以包含小數,有些則不能。
防止用戶輸入小數量的最佳方法是什么? (除了警告框並將字段設置為零)?
截取字段的鍵事件,在輸入時檢測非法字符,防止它們進入字段並在字段附近添加臨時消息(插入頁面),以解釋允許的字符或值。 彈出警報是在打字過程中提供反饋的不好方法。
然后,在提交之前再次進行驗證,因為還有其他方法可以將數據導入字段(拖放,復制/粘貼等等),這些方法可能無法捕獲所有內容。
這是一個只有整數和僅十進制字段的jQuery示例,當鍵入無效鍵時顯示臨時消息:
工作jsFiddle: http : //jsfiddle.net/jfriend00/CkDTy/
$(".integer").keypress(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return(false);
}
});
$(".decimal").keypress(function(e) {
// 46 is a period
if (e.which != 46 && (e.which < 48 || e.which > 57)) {
showAdvice(this, "Decimal numbers only");
return(false);
}
if (e.which == 46 && this.value.indexOf(".") != -1) {
showAdvice(this, "Only one period allowed in decimal numbers");
return(false); // only one decimal allowed
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove();
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500);
}
這是一個防止非數字輸入的小jQuery:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if(currValue.search(/[^0-9]/) != -1)
{
// Change this to something less obnoxious
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
});
});
您可以添加事件(按下按鍵)並檢測用戶是否按下了小數點。 同樣在表單提交時,使用正則表達式檢查提交的數據是否正確(因為用戶可以使用像firebug這樣的實時編輯器偽造數據)。 如果用戶禁用了javascript,請務必仔細檢查服務器端。
例如:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
你最好使用相同的函數,因為它基本上是相同的東西,並從兩個事件中調用它。
在服務器端,再次檢查提交的數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.