我的网站上有一个订单页面。某些订单商品可以包含小数,有些则不能。
防止用户输入小数量的最佳方法是什么? (除了警告框并将字段设置为零)?
答案 0 :(得分:14)
拦截字段的键事件,在输入时检测非法字符,防止它们进入字段并在字段附近添加临时消息(插入页面),以解释允许的字符或值。弹出警报是在打字过程中提供反馈的不好方法。
然后,在提交之前再次进行验证,因为还有其他方法可以将数据输入到字段中(拖放,复制/粘贴等等),这些方法可能无法捕获所有内容。
这是一个只有整数和仅十进制字段的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);
}
答案 1 :(得分:0)
这是一个防止非数字输入的小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]/, ''));
});
});
答案 2 :(得分:-1)
您可以添加一个事件(按下按键)并检测用户是否按下了小数点。同样在表单提交时,使用正则表达式检查提交的数据是否正确(因为用户可以使用像firebug这样的实时编辑器伪造数据)。如果用户禁用了javascript,请务必仔细检查服务器端。
例如:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
你最好使用相同的功能,因为它基本上是一样的,并从两个事件中调用它。
在服务器端,再次检查提交的数据