Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

JavaScript/REGEX: Decimals Fail Number Validation without Leading 0

Posted on 2014-01-21
3
Medium Priority
?
393 Views
Last Modified: 2014-01-21
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.
0
Comment
Question by:hankknight
3 Comments
 
LVL 85

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 39796795
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
 
LVL 83

Assisted Solution

by:leakim971
leakim971 earned 400 total points
ID: 39796801
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
 
LVL 43

Accepted Solution

by:
David S. earned 1200 total points
ID: 39796805
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

927 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question