Joseph Shambrook
Joseph Shambrook

Reputation: 321

Regex check for digits with decimal place

I have a regex in place for checking a price being entered. The price can not be a 5 figure sum or more, but can contain an option decimal number. So -

This is what I have so far, which is checking the number of decimals correctly, but isn't checking the amount of digits before the decimal place. What am I doing wrong?

var reg = new RegExp("^(\d{0,4})+(\.[0-9]{2})?$");

Upvotes: 0

Views: 2864

Answers (1)

stema
stema

Reputation: 92986

You have a wrong quantifier

var reg = new RegExp("^(\d{0,4})(\.[0-9]{2})?$");

just remove the + and your regex is fine.

See it here on Regexr

With this (\d{0,4})+ you are repeating your first group, so you can match any amount of digits before the dot.

Your jsfiddle works for me, if I double escape

var reg = new RegExp("^\\d{0,4}(?:\\.\\d{2})?$");

or don't put your regex in a string

var reg = new RegExp(/^(\d{0,4})(\.[0-9]{2})?$/);

Upvotes: 3

Related Questions