1

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

http://jsfiddle.net/FCHwx/

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?

Community
  • 1
  • 1
ChrisCa
  • 10,876
  • 22
  • 81
  • 118
  • The 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? –  Feb 28 '13 at 11:52

4 Answers4

7

This should be work

var regex = /^\d+(\.\d{1,2})?$/i;
Prashant16
  • 1,514
  • 3
  • 18
  • 39
  • it doesn't seem to - try it in the jsfiddle above – ChrisCa Feb 28 '13 at 11:56
  • @ChrisCa [yes it does](http://jsfiddle.net/barney/StH4F/). Besides, [108 StackOverflow users can't be wrong](http://stackoverflow.com/a/308124/356541), can they? ;) – Barney Feb 28 '13 at 11:57
  • the 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 – ChrisCa Feb 28 '13 at 12:00
  • @ChrisCa the `i` modifier has no influence here, it changes letters to match case independent, no letters, no influence on the regex. – stema Feb 28 '13 at 12:03
  • yeah - 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). – ChrisCa Feb 28 '13 at 12:04
  • 1
    @ChrisCa, for me it makes no difference (as it should) [jsfiddle](http://jsfiddle.net/FCHwx/8/) – stema Feb 28 '13 at 12:08
  • the reg ex linked to in the other question doesn't have the trailing slash that your jsfiddle has - that seems to be the problem – ChrisCa Feb 28 '13 at 12:13
3

Have you tried this?

var regex = /^[0-9]+\.[0-9]{0,2}$/i;
orique
  • 1,295
  • 1
  • 27
  • 36
  • you 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 Feb 28 '13 at 11:55
  • This would allow also "1." as valid input. – stema Feb 28 '13 at 12:04
1

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
Wouter J
  • 41,455
  • 15
  • 107
  • 112
0

Try this:

\d+(\.\d{1,2})?

d is for digit d{1,2} is for 1 digit before . and at least 2 digits such as 0.51

simple-thomas
  • 671
  • 7
  • 20