[英]regex check for Float number -> not ending and stars with decimal point
I am facing issues with regex pattern for Float number -> that should not end or stars with decimal points..我正面临浮点数正则表达式模式的问题 - >不应该结束或带小数点的星号..
I have tried following regex patter.. that is我试过遵循正则表达式模式..那就是
regex = /^\d*\.?\d*$/
// on doing // 在做
regex.test(11.)
regex.test(.11)
// it is returning true in checking // 它在检查时返回 true
// I need to make this as false, comment will be much helpful thank you. // 我需要将其设为 false,评论会很有帮助,谢谢。
You should bear in mind that regex only works with strings.您应该记住正则表达式只适用于字符串。 When you pass a non-string variable as input to a
RegExp
, it will first coerce it to a string type.当您将非字符串变量作为输入传递给
RegExp
时,它将首先将其强制转换为字符串类型。
Have a look:看一看:
console.log(11. , 'and', .11); // => 11 and 0.11
So, the actual string values you pass to your ^\d*\.?\d*$
regex are 11
and 0.11
that can be matched with the given pattern.因此,您传递给
^\d*\.?\d*$
正则表达式的实际字符串值是11
和0.11
,它们可以与给定模式匹配。 Actually, ^\d*\.?\d*$
is a regex that is usually used for a very loose live number input validation, eg see How to make proper Input validation with regex?实际上,
^\d*\.?\d*$
是一个正则表达式,通常用于非常松散的实时数字输入验证,例如,请参阅如何使用正则表达式进行正确的输入验证? . .
What you want is to implement a final, on-submit validation pattern, so that it could not pass strings like 11.
and .11
.您想要的是实现最终的提交时验证模式,以便它无法传递
11.
和.11
之类的字符串。 There have been lots of threads discussing this kind of regex:有很多线程讨论这种正则表达式:
Basically, for validation, you will need something like基本上,为了验证,您需要类似
/^\d+(?:\.\d+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]{1,2})?$/.test(input_string) // Some need to only allow 1 or 2 fractional digits
/^[0-9]{1,3}(?:\.[0-9]{2})?$/.test(input_string) // 1-3 digits in the integer part and two required in the fractional part
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.