【发布时间】:2024-01-31 06:05:01
【问题描述】:
我已经阅读了几个关于此主题的问题[1]、[2]、[3],但似乎没有一个问题可以为这个问题提供通用解决方案。所有答案似乎都针对某些特定情况。
我有这个简单的输入框
<input type="number" id="inputBox" min="0" max="255" step="1" />
我对其进行了严格的输入验证:
inputBox.addEventListener("input", function () {
validateInput(this);
});
inputBox.addEventListener("keydown", function (e) {
validateInput(this, e);
});
function validateInput(elm, e) {
// handle keydown event
if (e) {
// do not allow floating-point numbers, if it's not expected
if (!isFloat(elm.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
}
// handle input event
else {
// do not allow leading zeros
while (elm.value.length > 1 && elm.value[0] === "0") {
elm.value = elm.value.toString().slice(1);
}
// input should be between min and max
if (elm.validity.rangeUnderflow) {
elm.value = elm.min;
}
else if (elm.validity.rangeOverflow) {
elm.value = elm.max;
}
}
}
对于用户输入来说,所有这些似乎都可以正常工作。
var inputBox = document.getElementById("inputBox");
inputBox.addEventListener("input", function() {
validateInput(this);
});
inputBox.addEventListener("keydown", function(e) {
validateInput(this, e);
});
function validateInput(elm, e) {
// handle keydown event
if (e) {
// do not allow floating-point numbers, if it's not expected
if (!isFloat(elm.step)) {
if (e.key == ".") {
e.preventDefault();
}
}
}
// handle input event
else {
// do not allow leading zeros
while (elm.value.length > 1 && elm.value[0] === "0") {
elm.value = elm.value.toString().slice(1);
}
// input should be between min and max
if (elm.validity.rangeUnderflow) {
elm.value = elm.min;
} else if (elm.validity.rangeOverflow) {
elm.value = elm.max;
}
}
}
function isFloat(f) {
var f = parseFloat(f);
var floor = Math.floor(f);
var fraction = f - floor;
if (fraction > 0) {
return true;
}
return false;
}
<input type="number" id="inputBox" min="0" max="255" step="1" />
但用户仍然可以通过编程方式修改输入字段值。用户可以通过控制台输入以下值来绕过验证,这些是无效/意外的值:
inputBox.value = "005";
inputBox.value = "2.5"
inputBox.value = "-05.5";
如果用户使用inputBox.value 更改字段值,则理想的解决方案是调用函数(例如validateProgrammaticInput())。
inputBox.value = -10; // magically call validateProgrammaticInput()
注意:我没有使用表单。没有提交按钮。这不会被发送到服务器。这是一个客户端应用程序。应实时验证价值。如果我想以编程方式修改字段值,我可以在我的代码中触发自定义事件来验证输入,但事实并非如此。我想要的是验证输入,如果用户以编程方式输入它。所以我的用例与问题无关。我想我应该在混淆之前指出这些。
【问题讨论】:
-
你可以为
inputBox.value定义setter,所以它会调用你的函数。 -
@IvanShmidt 你能提供一个可行的例子吗?也许是JSFiddle?
-
@IvanShmidt 我认为这不会有帮助。这仅允许编程输入。如果我通过 UI 在字段中输入数字,则无法使用
inputBox.value获取输入的值,因为重新定义value属性会破坏输入字段的行为。 -
jsfiddle.net/4wfjk1hh/2 - 以编程方式和通过 UI 工作
标签: javascript html validation input event-handling