0

I need a regex for validating a string / decimal in JavaScript.

Which can be max 9 elements long with 2 decimals

Simply

123 - valid
123456789 - valid
1234567896 - invalid ( max 10 chars )

123. - invalid
123.2 - valid
123.32 valid
123.324 invalid ( 3 decimal points )

So I wrote a regexp like this

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

Can any one plz fine tune this regex

2
  • So 12345678.12 should be invalid? Commented Sep 29, 2015 at 10:57
  • what about leading zeros? is 0123 valid? Commented Sep 29, 2015 at 10:58

4 Answers 4

2

You can use regex ^(?=.{0,10}$)\d{0,9}(\.\d{1,2})?$

$('input').on('input', function() {
  $(this).css('color', this.value.match(/^(?=.{0,10}$)\d{0,9}(\.\d{1,2})?$/) ? 'green' : 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type=text/>

Regex explanation here

Regular expression visualization

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

1 Comment

The max number of characters this regex allows is 12. It should be 9.
2

Give the following a try:

^\d{1,9}(\.\d{1,2})?$

1 Comment

The max number of characters this regex allows is 12. It should be 9.
1

Something like this?

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

3 Comments

The max number of characters this regex allows is 12. It should be 9.
Did you interpret the question like that? I thought he meant it can be 9 characters long plus two decimals.
Which can be max 9 elements long with 2 decimals
1

You may use a negative lookahead at the beginning to apply a length restriction to the whole match:

^(?!\S{10})\d+(?:\.\d{1,2})?$

See regex demo

  • ^ - start of string
  • (?!\S{10}) - no more than 9 non-whitespace characters from the beginning to end condition
  • \d+ - 1 or more digits
  • (?:\.\d{1,2})? - 1 or zero groups of . + 1 or w2 digits
  • $ - end of string

However, you might as well just match the float/integer numbers with ^\d+(?:\.\d{1,2})?$ and then check the length of the matched text to decide whether it is valid or not.

Note that in case you have to omit leading zeros, you need to get rid of them first:

s = s.replace(/^0+/, '');

And then use the regex above.

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.