Reputation: 523
I am trying to write a regex to validate a decimal number.
This regex validates what comes before the decimal place
^(?:[1-9][0-9]{0,4}|0)$
This regex validates what comes after the decimal place
^[0-9]{1}+$
I just don't know how to combined the two such that the decimal place is mandatory.
How do I solve this problem?
Upvotes: 2
Views: 2352
Reputation: 35603
That should work
const r = /^(?:[1-9]\d{0,4}|0)\.\d+/
const arr = ['0', '1', '1.2', '1.', '1.123', '0123.1', '123.123', '1234.1', '12345.12345678', '123456.123', '0.12'];
arr.forEach((val) => {
console.log(val, r.test(val));
})
Upvotes: 0
Reputation: 27763
This RegEx might validate your inputs:
^(\d{1,5}\.\d{1,})$
and you can simply call it using $1.
Upvotes: 0
Reputation:
To the best of my knowledge, this works
^(?:[1-9]\d{0,4}|0)\.\d$
Expanded
^ # BOS
(?:
[1-9] \d{0,4} # 1-5 digits, must not start with 0
| # or,
0 # 0
)
\. \d # decimal point and 1 digit
$ # EOS
Upvotes: 4