简体   繁体   中英

Regex only allow whole and decimal point numbers

I want an input field that only receives whole and decimal point numbers greater than 2.5

const [foreignPackageWeight, setForeignPackageWeight] = useState('')

<input type="text" value={foreignPackageWeight}
  onChange={(e) => {
    setForeignPackageWeight(e.target.value.replace(/[^0-9.]/g, ''))
  }}
/>

But my regex allows for numbers like .1 , ..2 , 3...4 , 5..... How do I change my regex to only allow one decimal point?

A possible solution is a form of lookaround known as a positive lookbehind. Lookarounds allow you to ensure a pattern exists (or doesn't exist) without that pattern becoming part of the results.

/[^0-9.]|(?<=\..*)\./g

Match any of:

  • [^0-9.] Anything that is not a digit or a period
  • (?<=\..*)\. A period so long as another period appeared earlier in the sequence

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