Regular Expression to accept only positive numbers and decimals
You can try this -
^\d{0,10}(\.\d{0,2})?$
Also one cool site to test as well as to get description of your own regular expressions https://regex101.com/
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
matches
0
+0
1.
1.5
.5
but not
.
1..5
1.2.3
-1
EDIT:
To handle scientific notation (1e6
), you might want to do
/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/
If you want strictly positive numbers, no zero, you can do
/^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$/
There are few different ways to do this depending on your need:
/^[0-9.]+$/
matches 1
and 1.1
but not -1
/^[0-9]+\.[0-9]+$/
matches 1.1
but not 1
or -1
Generally, I recommend using a simple regExp reference guide like http://www.regular-expressions.info/ for building expressions, and then test them using javascript right your browser console:
"123.45".match(/^[0-9.]+$/)