繁体   English   中英

最大数为 100 的正则表达式,删除第二个点并将最大位数限制为 6

[英]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 无效

数字的输入类型理论上应该不允许您输入包含多个基数字符 ( . ) 的数字。 对于您的其他两个要求,与其使用正则表达式,不如这样做更直观、更简单:

  • 评估为字符串以确保它不超过 6 个字符,并且
  • 评估为一个数字以确保它的值不超过 100

请参阅下面的概念验证:

 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})?)$

...验证:

  • [0..100] 中的值
  • 单个数字后跟最多 5 个可选小数
  • 两位数字后跟最多 4 个可选小数
  • 100 后跟最多 3 个可选的 0

见: https : //regex101.com/r/PWseLS/1

暂无
暂无

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

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