简体   繁体   中英

Regular Expression Allowing Input For Only Numbers and One Decimal

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.

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.

Try this:

/^\d+(\.\d+)?$/

Should work for any positive decimal number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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