Solved

JavaScript/REGEX: Decimals Fail Number Validation without Leading 0

Posted on 2014-01-21
3
362 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 84

Assisted Solution

by:ozo
ozo earned 100 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 82

Assisted Solution

by:leakim971
leakim971 earned 100 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 42

Accepted Solution

by:
David S. earned 300 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Do you hate spam? I do, and I am willing to bet you do as well. I often wonder, though, "if people hate spam so much, why do they still post their email addresses on the web?" I'm not talking about a plain-text posting here. I am referring to the fa…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…

776 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