javascript 如何在 ReactJS 中验证输入类型 =“数字”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31992169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:42:49  来源:igfitidea点击:

How to validate input type="number" in ReactJS?

javascripthtmlvalidationreactjs

提问by Anatoli

I have a problem with validation of HTML element input type="number"in ReactJSApplication:

我在ReactJS应用程序中验证 HTML 元素输入 type="number"遇到问题

render() {
    return (
        <input type="number" onBlur={this.onBlur} />
    );
},

onBlur(e) {
    console.log(e);
}

The log is:

日志是:

enter image description here

在此处输入图片说明

Everything is ok on desktop application, but on mobile there is a problem. User can change the keyboard and enter everything he wants. So I wanted to fix it using validation. When I try to catch the value the user enter, I get this log. It's like React is just hiding this incorrect value.

在桌面应用程序上一切正常,但在移动设备上存在问题。用户可以更改键盘并输入他想要的任何内容。所以我想使用验证来修复它。当我尝试捕捉用户输入的值时,我得到了这个日志。就像 React 只是隐藏了这个不正确的值。

How can I fix it? Or there is another way how to validate input type="number"in ReactJSApplication?

我该如何解决?或者还有另一种方法如何在ReactJS应用程序中验证输入类型 =“数字”

Thanks in advance.

提前致谢。

采纳答案by Anatoli

It's the best way how to validate:

这是验证的最佳方式:

<input type="number" pattern="[0-9]*" inputmode="numeric">

In this way I can't enter smth else. Moreover e.target.valuewith checking on nullcan't get good fixed result because empty field and the field with not correct text are the same (empty).

这样我就不能进入其他了。此外,检查空值的e.target.value无法获得良好的固定结果,因为空字段和文本不正确的字段是相同的(空)。

回答by agmcleod

You can access the value through:

您可以通过以下方式访问该值:

e.target.value;

I don't recall if on mobile if it passes an empty value if it's not a number like on desktop. But just do your checks against it. Don't let the form submit unless it's all valid :)

我不记得是否在移动设备上如果它不是像桌面上那样的数字,它会传递一个空值。但只要对它进行检查。除非表单全部有效,否则不要让表单提交:)