I want an input text box that restricts users to only enter numbers and one decimal point.
The regular expression I am using currently is /[^d.]/g
.
Currently this allows the user to only input numbers and decimals but also allows for more than one decimal number. I am using it for a text box to allow only a string of numbers along with one decimal following another string of numbers but ends.
Text box code:
onkeyup= "this.value=this.value.replace(/[^d.]/g, '' )"
.
Full html block:Enter your second number <input type="text" id="num2" onClick="(this.value='')" onkeyup= "this.value=this.value.replace(/[^d.]/g, '' )" />
I have this expression here that highlights what I’m looking for /^d+(.d+)?/gm
it’s just I need it completely in-versed.
/^d+(.d+)?/gm /d+(.d+)/gm /(^d+[.]d+)+[d]+/gm
The preceding expressions allow input for everything but numbers and decimals. I need to allow only numbers and decimals for input.
I have seen others but none seem to accomplish exactly what I am looking for. I don’t not want to allow negative numbers either but would like it optional.
- 12.00 – yes
- .124 – no
- -.07 – no
- -65 – no
- 124456 – yes
- 143467985.65534568746 – yes
Any guidance would be appreciated. Thanks for the help.
Advertisement
Answer
I think the expression you are looking for is /^d+(.)?d+/gm
You can view it with the test cases you provided on regex101, here
EDIT: As @Konrad Linkowski pointed out this does not work for single digits such as
1
. The updated regex(^.*)+(^0*)+^d+(.d+)?
includes this edge case.