如何检测输入字段上的程序化值变化 [英] How to detect programmatic value change on input field

查看:73
本文介绍了如何检测输入字段上的程序化值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几个问题 [1] [2] [3] 关于此主题,但似乎没有一个提供此问题的一般解决方案.所有答案似乎都针对某些特定情况.

I've read several questions [1], [2], [3] regarding this topic, but none seems to provide a general solution to this problem. All answers seems to be directed to some specific cases.

我有这个简单的输入字段

I have this simple input field

<input type="number" id="inputBox" min="0" max="255" step="1" />

我对此进行了严格的输入验证:

and I do a strict input validation on it:

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;
        }
    }
}

所有这些似乎都可以很好地用于用户输入.

All this seems to be working fine for user input.

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" />

但是用户仍然可以通过编程方式修改输入字段的值.用户可以通过控制台输入以下值来绕过验证,这些值是无效/意外值:

But the user can still modify the input field value programmatically. The user can enter the following values through the console to bypass the validation and these are invalid/unexpected values:

inputBox.value = "005";
inputBox.value = "2.5"
inputBox.value = "-05.5";

对此的理想解决方案是,如果用户使用inputBox.value更改字段值,则调用一个函数(例如validateProgrammaticInput()).

An ideal solution to this would be to call a function (e.g. validateProgrammaticInput()) if the user changes the field value using inputBox.value.

inputBox.value = -10; // magically call validateProgrammaticInput()


注意:我没有使用表格.没有提交按钮.这将不会发送到服务器.这是一个客户端应用程序.价值应实时验证.如果 I 要以编程方式修改字段值,则可以在代码中触发一个自定义事件以验证输入,但实际情况并非如此.我要验证的是输入(如果用户以编程方式输入).因此,我的用例与该问题无关.以为我应该在混乱之前指出这些.

推荐答案

您可以像这样更改值后以编程方式触发事件

you can trigger the event programmaticaly after changing the value like this

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>

这篇关于如何检测输入字段上的程序化值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆