1

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

// I need to make this as false, comment will be much helpful thank you.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Anupam Maurya
  • 1,927
  • 22
  • 26
  • 2
    That is because all parts are optional. You can use `^\d+(?:\.\d+)?$` to match an optional dot and digits. – The fourth bird Apr 13 '21 at 18:50
  • hey @Thefourthbird can you correct me if you can? because I need to understand it. Thanks! – Anupam Maurya Apr 13 '21 at 18:52
  • 2
    In your pattern you use `*` which means 0 or more, and `?` which means 0 or 1. So it can match for example also a single dot or an empty string. So you have to match at least a single digit, followed by an optional part matching a dot and digits so it can also not end on a dot only. There are examples like this page which have examples and explanations https://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2 – The fourth bird Apr 13 '21 at 18:58
  • 1
    `11.` will get parsed as `"11"` string and `.11` as `"0.11"`. Pass the values as strings and use `^\d+(?:\.\d+)?$`. – Wiktor Stribiżew Apr 13 '21 at 19:19
  • it seems i needs to put 5hrs to understand regex concept.. – Anupam Maurya Apr 13 '21 at 19:31
  • 1
    Regex only operates on strings, so all numbers you pass to it are coerced to strings. – Wiktor Stribiżew Apr 13 '21 at 19:34

1 Answers1

2

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.

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. Actually, ^\d*\.?\d*$ is a regex that is usually used for a very loose live number input validation, e.g. see How to make proper Input validation with regex?.

What you want is to implement a final, on-submit validation pattern, so that it could not pass strings like 11. and .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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563