0

I'm having problem with JavaScript regular expressions. I want to match real numbers form 1 to 5. Precission is in two digits. My code is but it doesnt work.

function validate_prosjek(nmb)
{
    var pattern= new RegExp(/[1-4]\.[0-9][0-9]|5\.00/);

    return pattern.test(nmb);
}

It recognizes real numbers higher than 5.

5
  • 1
    regular-expressions.info/floatingpoint.html Commented Apr 23, 2013 at 22:12
  • Please note that none of that has anything to do with jQuery, this is all Javascript functionality. This information should help you search for what you're looking for next time. Commented Apr 23, 2013 at 22:16
  • Works on my machine. Tested with regexpal.com Commented Apr 23, 2013 at 22:16
  • @RobertHarvey it can't work - it's not restrictive enough and will fail to ignore any extra numeric digits on either end of the number. Commented Apr 23, 2013 at 22:18
  • @MikeM yes, you're right (sigh) Commented Apr 23, 2013 at 22:32

1 Answer 1

2

You need to "anchor" your regexp with ^ and $ to match the beginning and end of the string, respectively:

var pattern = /^([1-4]\.[0-9][0-9]|5\.00)$/;

You also need to escape the . because it's a special character in regexps, and there's no need to call new RegExp if the regexp is already in /.../ synax.

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

8 Comments

@MikeM ok, so it does - I found a test case where it didn't work.
/^[1-4]\.[0-9][0-9]|^5\.00$/
Final version.Works fine. Your fail on cases where second digit is 5 and number is grater than 10, such as 15.00 25.00 and so long
@BodoHombah no, like Ansgar and MikeM pointed out, you need a group around the two alternatives.
the version that's been there for the last five minutes does not have that problem. You must have the () group.
|

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.