views:

87

answers:

5

I'm trying to create a JavaScript Regex to test for:

a valid # between 0 and 99.9 (where only a single decimal digit is allowed) e.g. 3.45 is not valid.

so, blank is ok, any integer between 0 and 99 is ok, and a decimal value is allowed.

I have this so far, but it is allowing values like 3.45 to pass:

$^|$[0-9][0-9]?^|$[0-9][0-9]?.[0-9]^
+9  A: 

Two problems I can see:

  • You mixed up ^ and $.
  • Your decimal point needs escaping \..
Mark Byers
doh! I would have spent all day fighting the inner matches - thanks for the head shake.
danny
+4  A: 

Mark already said what is wrong with your expression. Here is another way how you could write it:

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

Explanation:

  • ^ matches the beginning of the string
  • (...)? makes the whole number optional
  • $ matches the end of the string
  • \d\d? matches either one or two digits (? makes the second one optional)
  • (\.\d)? matches a dot . and a digit (? makes it optional)
Felix Kling
+1  A: 

I've never really used much JavaScript, but this should do the job...

^[0-9][0-9]?(?:\.[0-9])?$
Cags
Oops, Felix Kling posted while I was typing, the two patterns are fairly similar though he took into account blank, which I didn't (missed that requirement).
Cags
Doesn't match empty string.
M42
You don't say... jeez.
Cags
+1  A: 

Rewrite your regex as :

^$|^[0-9][0-9]?$|^[0-9][0-9]?\.[0-9]$

But better, use Felix King's one.

M42
A: 

Another variant is

/^\d{0,2}(\.\d)?$/

which will accept numbers like .3 if such are to be allowed.

Hans B PUFAL