Solved

JavaScript/REGEX: Decimals Fail Number Validation without Leading 0

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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…

840 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