RMN
RMN

Reputation: 752

Regular Expression not working as expected in javascript

I have following regular expression: ^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)

It should not allow 4 digit number such as 4444. The expression is working fine if I try here, but in javascript, the code is not working as expected. It is allowing 4 digit numbers. All other validations work fine.

Here is my code:

http://jsfiddle.net/PAscG/

reg0str = "^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)";
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;

UPDATE TO EXPLAIN Functionality:

I want to allow only 3 digits. So either I can allow only 1 digit after decimal and 2 before decimal or I can allow max of 3 digits before decimal and nothing after decimal.

So my first part:
[0-9]{0,3}$ I assume this should allow a max of 3 digits and only numbers.

Next part: [0-9]{0,2}\.?[0-9]{0,1}$ should allow max of 2 digits before decimal and a max of 1 digit after decimal.

Upvotes: 0

Views: 1879

Answers (3)

HBP
HBP

Reputation: 16063

Following OP's clarification

The regexp is

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

  ^        start of string
  -?       optional minus sign (use [-+]? if you accept a plus sign)
  (        start of OR group
    \d{0,3}  0 1, 2 or 3 digits
    \.?      optional decimal point
  |        OR
    \d{0,2}  0 1, or 2 digits
    \.       decimal point
    \d       final decimal
  )        end of OR grouping
  $        end of string

Upvotes: 1

Bergi
Bergi

Reputation: 665455

"…\.…" is a string literal - the backslash escapes the dot to a dot and the regex dot matches a digit. You would need to escape the backslash to pass a string with a backslash in the RegExp constructor:

new RegExp("^-?([0-9]{0,3}$|[0-9]{0,2}\\.?[0-9]{0,1}$)")

or you use a regex literal (simplified, but still matching the same):

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

Upvotes: 1

Zach Lesperance
Zach Lesperance

Reputation: 347

Try this:

 var reg0str = "^\-?[0-9]{0,2}[\.]?[0-9]?$";

I'm not sure why, but the period seems to be being treated as the wildcard character if not encapsulated within a class.

Here's the updated jsfiddle

Upvotes: 1

Related Questions