JavaScript/REGEX: Decimals Fail Number Validation without Leading 0

This verifies an a string contains a number and only a number:
str.match(/^-?[0-9]\d*(.\d+)?$/g) 

Open in new window

However these numbers fail:
.5
-.5

Open in new window

They pass if there is a 0 before the decimal but I would like it to pass with or without the leading 0.
LVL 16
hankknightAsked:
Who is Participating?
 
David S.Connect With a Mentor Commented:
isNaN() would allow empty strings and strings only containing white-space characters though.

This should do it:
/^-?(\d*\.)?\d+$/g

Open in new window

0
 
ozoConnect With a Mentor Commented:
You can omit the [0-9]
but then these would also verify as numbers:
-

Open in new window


If you want at least one digit either before or after the decimal point, you might try something like
/^-?(\d+\.?|\.\d)\d*$/
0
 
leakim971Connect With a Mentor PluritechnicianCommented:
What not using isNaN ?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

isNaN("R")
true
isNaN("1")
false
isNaN("-1")
false
isNaN("-1f")
true
isNaN("1f")
true
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.