Solved

JavaScript/REGEX: Decimals Fail Number Validation without Leading 0

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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…

707 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now