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 about 3 hoursIn 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 over 9 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 over 9 yearsyou can use\dinstead 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 over 9 yearsthe 3 means 3 decimals, he wants only 2. -
ChrisCa over 9 yearsit doesn't seem to - try it in the jsfiddle above -
Barney over 9 years@ChrisCa yes it does. Besides, 108 StackOverflow users can't be wrong, can they? ;) -
ChrisCa over 9 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 over 9 yearsright, thought it meant 3 chars in total minimum -
stema over 9 years@ChrisCa theimodifier has no influence here, it changes letters to match case independent, no letters, no influence on the regex. -
ChrisCa over 9 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 over 9 yearsThis would allow also "1." as valid input. -
stema over 9 years@ChrisCa, for me it makes no difference (as it should) jsfiddle -
ChrisCa over 9 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