[英]Regex for max number 100, removing the second dot and restrict maximum digits to 6
我需要验证输入类型号中的值。 我已经这样做了,但这很脏
const value = ev.target.value
if (value > 100 || (value.length === 2 && +value[0] === 0)) ev.target.value = value.slice(0, value.length - 1)
我需要以这种方式验证字段 12.3.3 无效 10.2 有效 100.2 无效
数字的输入类型理论上应该不允许您输入包含多个基数字符 ( .
) 的数字。 对于您的其他两个要求,与其使用正则表达式,不如这样做更直观、更简单:
请参阅下面的概念验证:
function isNumberValid(num) { // Restrict to max 6 digits if (num.replace(/[^0-9]/, '').length > 6) { return false; } // Cap value at 100 if (+num > 100) { return false; } return true; } document.querySelector('#input').addEventListener('input', e => { const isValid = isNumberValid(e.currentTarget.value); console.log(isValid); });
<input type="number" id="input" />100.10.1
^(\\d{1}(?:\\.\\d{1,5})?|\\d{2}(?:\\.\\d{1,4})?|100(?:\\.0{1,3})?)$
...验证:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.