ramesh
ramesh

Reputation: 4082

JavaScript regex for custom validation

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

Upvotes: 0

Views: 782

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

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.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

Upvotes: 2

Orry
Orry

Reputation: 659

Something like this?

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

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80639

Give the following a try:

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

Upvotes: 2

Related Questions