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
Share:
13,116
ChrisCa
Author by

ChrisCa

Updated on November 23, 2022

Comments

  • ChrisCa
    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

    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?

    • Admin
      Admin about 11 years
      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?
  • Wouter J
    Wouter J about 11 years
    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
    Wouter J about 11 years
    the 3 means 3 decimals, he wants only 2.
  • ChrisCa
    ChrisCa about 11 years
    it doesn't seem to - try it in the jsfiddle above
  • Barney
    Barney about 11 years
    @ChrisCa yes it does. Besides, 108 StackOverflow users can't be wrong, can they? ;)
  • ChrisCa
    ChrisCa about 11 years
    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
  • simple-thomas
    simple-thomas about 11 years
    right, thought it meant 3 chars in total minimum
  • stema
    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
    ChrisCa about 11 years
    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).
  • stema
    stema about 11 years
    This would allow also "1." as valid input.
  • stema
    stema about 11 years
    @ChrisCa, for me it makes no difference (as it should) jsfiddle
  • ChrisCa
    ChrisCa about 11 years
    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