javascript - 如何检测输入字段上的编程值变化

标签 javascript html validation input event-handling

我已经阅读了几个问题 [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()
<小时/>

注意:我没有使用表单。没有提交按钮。这不会被发送到服务器。这是一个客户端应用程序。值(value)应该实时验证。如果想要以编程方式修改字段值,我可以在代码中触发自定义事件来验证输入,但事实并非如此。我想要的是验证输入(如果用户以编程方式输入)。所以我的用例与问题无关。我想我应该在困惑之前指出这些。

最佳答案

您可以在更改值后以编程方式触发事件,如下所示

var inputBox = document.getElementById("inputBox");
inputBox.addEventListener("input", function () {
  console.log("input");
    // input should be between min and max
    if (this.validity.rangeUnderflow) {
        this.value = this.min;
    }
    else if (this.validity.rangeOverflow) {
        this.value = this.max;
    }
    // do not allow leading zeros
    while (this.value.length > 1 && this.value.toString()[0] === "0") {
        this.value = this.value.toString().slice(1);
    }
});

inputBox.addEventListener("keydown", function (e) {
    // do not allow floating-point numbers, if it's not expected
    if (!isFloat(this.step)) {
        if (e.key == ".") {
            e.preventDefault();
        }
    }
},false);

function change(){
  inputBox.value = "005";
  inputBox.dispatchEvent(new Event('input'));
}

function isFloat(n){
    return Number(n) === n && n % 1 !== 0;
}
<input type="number" id="inputBox" min="0" max="255" step="1" />

<button onclick="change()">change</button>

关于javascript - 如何检测输入字段上的编程值变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249781/

相关文章:

javascript - 如何在客户端正确使用 Stripe api 保存卡片

JavaScript的执行顺序

html - ul -> 一条规则不应该影响 child ul -> a

javascript - anchor 标记在 gmail 附件中不起作用

validation - 如何在 Angular 中测试表单验证

javascript - 函数不能在while循环中实现吗?

javascript - 如何在加载了 jquery mobile 的每个页面上执行相同的 javascript 函数

jquery - 在 IE9 中隐藏默认选择下拉箭头

validation - JideFX 验证器不起作用

javascript - jQuery 仅按字母顺序与数字