Javascript Regex for decimals
13,116
Solution 1
This should be work
var regex = /^\d+(\.\d{1,2})?$/i;
Solution 2
Have you tried this?
var regex = /^[0-9]+\.[0-9]{0,2}$/i;
Solution 3
I recommend you to not use REGEX for this, but use a simple !isNaN
:
console.log(!isNaN('20.13')); // true
console.log(!isNaN('20')); // true
console.log(!isNaN('20kb')); // false
Author by
ChrisCa
Updated on November 23, 2022Comments
-
ChrisCa over 1 year
In Javascript, I am trying to validate a user input to be only valid decimals
I have the following JSFiddle that shows the regex I currently have
var regex = /^[0-9]+$/i; var key = '500.00'; if (key.match(regex) != null) { alert('legal'); } else { alert('illegal'); }
This works fine for integers. I need to also allow decimal numbers (i.e. up to 2 decimal places)
I have tried many of the regex's that can be found on stackoverflow e.g. Simple regular expression for a decimal with a precision of 2
but none of them work for this use case
What am I doing wrong?
-
Admin about 11 yearsThe question you linked to seems to do exactly what you want. Can you explain why those don't work, including showing the input that they fail on?
-
-
Wouter J about 11 yearsyou can use
\d
instead of[0-9]
too, it don't think it makes much difference, but I think it is a good practise to use those predefined character classes -
Wouter J about 11 yearsthe 3 means 3 decimals, he wants only 2.
-
ChrisCa about 11 yearsit doesn't seem to - try it in the jsfiddle above
-
Barney about 11 years@ChrisCa yes it does. Besides, 108 StackOverflow users can't be wrong, can they? ;)
-
ChrisCa about 11 yearsthe one you link to works - it is slightly different to the one above (it has a /i on the end which seems to do the trick - thanks
-
simple-thomas about 11 yearsright, thought it meant 3 chars in total minimum
-
stema about 11 years@ChrisCa the
i
modifier has no influence here, it changes letters to match case independent, no letters, no influence on the regex. -
ChrisCa about 11 yearsyeah - i did try that one - I even linked to it in the question. but it needs a little tweak to work in my use case (the /i).
-
stema about 11 yearsThis would allow also "1." as valid input.
-
stema about 11 years@ChrisCa, for me it makes no difference (as it should) jsfiddle
-
ChrisCa about 11 yearsthe reg ex linked to in the other question doesn't have the trailing slash that your jsfiddle has - that seems to be the problem