0

I'm using this regex to validate float numbers:

var reg = /\d+\.?\d+/;

But it's validating this as true:

"11.34x"
"11.34abs"
"1a1.34abs"

The \d should only match numbers. What is happening?

2
  • So do you check for float numbers only? \.? means that it might be an integer value as well (though with minimum of 2 digits). Commented Feb 16, 2013 at 0:06
  • Do you want to allow scientific notation, like -1e-10? Commented Feb 16, 2013 at 0:24

4 Answers 4

2

If you don't anchor the regular expression, it will match a string that contains a substring that matches.

Try:

var reg = /^\d+\.?\d+$/;

The ^ matches the start of the test string, and $ matches the end. Thus that regular expression will only match strings that have nothing but digits and at most one ".".

edit — as pointed out, your use of the + quantifier means your regex requires digits; if there's a decimal point, then it requires digits on both sides. Maybe that's what you want, maybe it isn't.

Sign up to request clarification or add additional context in comments.

6 Comments

your regex is not match single digit 0-9
@burning_LEGION ha well I just copied his :-) You're right however. Thanks, I'll update
... yeah, and maybe it is not the best way to validate float numbers.
@VisioN agreed - I'll add that too edit oh wait somebody else points that out.
Not the best approach though... I'd use parseFloat(n) === +n but only if the OP wants to check all number types, not only floats (considering his ? in regex).
|
2

use this regular expression ^\d+(\.\d+)?$

or ^\d+([.,]\d+)?$ separator can be comma or dot

Comments

1

Consider using the Number wrapper/constructor function instead:

Number('11.34'); // => 11.34
Number('11.34x'); // => NaN

[Edit] As commenter @VisioN points out, that function has an edge case for empty and pure-whitespace strings, so maybe create a wrapper function:

function reallyParseFloatingPointNumber(s) {
  var s = (''+s).trim();
  return (s==='') ? NaN : Number(s);
}

2 Comments

Bad idea. Number("") === Number(" ") === 0. And it won't work for floats only.
Arrggg... damn you, JavaScript!
0
if (!"12 34.98 ".replace(/^\s+|\s+$/g,"").match(/^\d+\.?\d+$/))
  alert("Please enter numbers in float form")
else alert ("Good Form, Old Chap!")

Alas, I am mistaken again! burning_LEGION is correct:

/^\d+(\.\d+)?$/  

will match single digits too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.