• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 416
  • Last Modified:

How to get regular expresson ti limirt number of digits to be entered by user

This would seem very simple because I only want my user to be able to enter up to 2 digits followed by a . char followed by up to 2 decimal places.

So in other words a floating point value such as 99.99 or 3.45 or 37.8 but not 888 or 888.88.

Now my Javascript regular expression to allow up to 2 digits before the floating point looks like this:

var regExp = /[0-9]{1,2}/

but what I don't understand is that this expression returns true when I call
regExp.test("888"); ?????

Can anyone explain this and tell me what I should be putting to ensure the 3rd digit causes an invalid result?

Many thanks

2 Solutions
/[0-9]{1,2}/ can match either the first 88 or the last 88 in "888"
would only allow . and not 8 after the first 88
yes its actually quite simple that you don't need a regular expression for that.  so according to this

>> So in other words a floating point value such as 99.99 or 3.45 or 37.8 but not 888 or 888.88.

you can
1) check whether the string has a decimal "." .
2) if there's decimal
     a) split the string on "." as delimiter.
     b) check 1st element and 2nd element whether they less than 99 and more than 0.

Samm1502Author Commented:
Thanks ghostdog74 but I have to use a regular expressions for reasons I won't bore you with and ozo if I read this correctly it test for the existence of any char not in the range [0-9] but I need to make sure my regexp.test call returns true if the entered value is valid and false otherwise so how do I alter my original expression to prevent it matching part of the entered string and force it match all of it i.e. allwo just 1 or 2 digits before the . and 1 or 2 digits afterwards?

Many thanks.
Terry WoodsIT GuruCommented:
In ozo's solution
the ^ matches the start of the string.

Altering it to restrict it to 1 or 2 digits after the decimal would be:

$ matches the end of the string.
Samm1502Author Commented:
Thanks for the explanation. Cheers Sam
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now