简体   繁体   English

HTML5输入类型编号+ oninput regex验证会擦除该字段,并按点

[英]HTML5 input type number + oninput regex validation erase the field pressing dot

I'm having problems with an input type number in HTML5 combining it with an oninput event to have an optional max length qith an optional n max decimals in it. 我在HTML5中将输入类型编号与oninput事件组合在一起时遇到问题,以在其中具有可选的最大长度qith和可选的n max个小数。 I have the following example code: 我有以下示例代码:

 <input type="number" name="name" step="any" oninput=" this.value = (this.value.length > 8) ? this.value.slice(0,8) : this.value; /^[0-9]+(.[0-9]{1,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0,-1); "> 

It works fine except that when a dot is pressed down it removes the entire number without any kind of error. 效果很好,只是当按下一个点时,它会删除整个数字,而没有任何错误。 It works with ',' but on mobile I will need the '.' 它可以与','一起使用,但在移动设备上,我将需要'。'。 for keyboard purposes. 用于键盘。 (I need that works too like now with ',') (我需要使用','就像现在一样工作)

Since you only want to control the length of the total number and of its decimal part, I would recommend the keydown event instead of the input event. 因为您只想控制总数及其小数部分的长度,所以我建议使用keydown事件而不是input事件。 The following expression 以下表达式

<input type="number" name="name" step="any" onkeydown=
"return event.keyCode<32 || this.value.length<8 && /^\d*([.,]\d{0,2})?$/.test(this.value)"
>
  • suppresses input if more than 8 characters 如果超过8个字符,则禁止输入
  • suppresses input if more than 3 decimals are entered 如果输入的小数点后3个以上,则禁止输入
  • allows special keys like backspace 允许特殊键,例如退格键
  • disallows non-numeric input (automatic by type="number" ) 禁止非数字输入(按type="number"自动输入)

Your main problem is your text disappearing if you enter a non-numeric character. 您的主要问题是,如果您输入非数字字符,则文本会消失。 (Depending on your browsers localization settings, a dot could be considered non-numeric.) The problem is that entering a non-numeric value puts the element into an invalid state, and the element's value cannot be retrieved . (取决于您的浏览器的本地化设置,点可能被视为非数字。)问题在于,输入非数字值会使元素处于无效状态,并且无法检索到元素的值。

Fortunately, HTML can do this validation by itself, using the step attribute. 幸运的是,HTML可以使用step属性自行执行此验证。 You don't get the satisfaction of bad characters being immediately erased, but the input will show as invalid once it loses focus. 您不满意立即删除不良字符,但是一旦失去焦点,输入将显示为无效。 And if needed, you can set custom error messages for the element. 并且,如果需要,您可以为元素设置自定义错误消息。

 <input id="identification" type="number" name="name" step="0.001" min="0" max="99999999" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM