1

I use the following pattern for decimal validation.

var pattern = /^([0-9]+)[.][0-9]{0,2}$/;

I need to enter only 10 digits. for example,

12345678.00

need to enter 8 digits before the dot. after dot,the 2 digits are optional. how to validate only enter 8 digits before dot symbol?

4
  • I know I already submitted an answer but I have a question that might cause me to edit it. What if the user enters 3 or 4 digits after the dot, do you want to match the first two or not? Commented Sep 19, 2013 at 16:23
  • 1
    Shouldn't the dot itself be optional as well? With at least 1 digit required after it, if it's present? Commented Sep 19, 2013 at 16:30
  • @JustinMorgan Although I upvoted your comment for pointing out the optional decimal point depending on whether or not there are digits after it, if you think about it, having a lone decimal point technically does not invalidate the entry as a valid number, if OP chooses to build his/her application this way. Commented Sep 19, 2013 at 16:42
  • @Nasser - Yeah, I think you could make good arguments for both allowing and disallowing the orphan decimal point. Personally, I'd call it invalid, but that's me. Commented Sep 19, 2013 at 19:06

4 Answers 4

1

Try this!

^[\d]{1,8}([\.|\,]\d{1,2})?$

Regards..

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

Comments

0

Try this:

/^[0-9]{8}[.][0-9]{0,2}\b/g

Basically means "exactly 8 digits before the dot, and up to 2 digits after the dot". Also, if you want some regexp shorthand, you can use \d which escapes digits

/^\d{8}[.]\d{0,2}\b/g

Also, this was not clear in your question: do you want to match the two digits after the decimal if the user enters 3 or more characters? If yes, then remove the \b part and it will work for you

Comments

0

Use

/^[0-9]{8}[.]([0-9]{2})?$/

This should make sure you have 8 digits before the dot, and exactly 0 or 2 digits after the dot.

Comments

0

It sounds like what you really want is this:

/^[0-9]{8}(\.[0-9]{1,2})?$/

You can also write it like this:

/^\d{8}(\.\d\d?)?$/

This pattern makes the dot optional, and if it's present, requires either one or two digits after it. The \d is shorthand for [0-9] (they're not identical in all regex flavors, but they are in JavaScript).

As you've written it, your pattern requires the decimal point, even if there are no decimal digits. So 12345678 will fail, while 12354678. will pass. That's probably not what you want; in fact, I doubt you'd consider the second number valid.

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.