Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for dollar amount in JavaScript

I know this has been done a thousand times before but I'm having trouble with getting this right. I need to format the value of a text input for dollar amounts. No commas should be allowed. Only two decimal places should be allowed. Examples of what should be allowed:

  • 100
  • 100.10
  • $100
  • $100.25

Below is my current incomplete regular expression. It currently allows multiple dollar signs to be included anywhere (not just at beginning), multiple decimal points to be included anywhere, and more than two decimal places which it shouldn't.

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="Javascript">
    $(function(){

        jQuery('.dollarAmountOnly').keyup(function () {
            this.value = this.value.replace(/[^$0-9\.]/g, '');
        });
    });
</script>
</head>
<body>
<input type="text" class="dollarAmountOnly"/>
</body>
</html>

I would greatly appreciate help. Thanks!

like image 283
SquidScareMe Avatar asked Jan 12 '12 03:01

SquidScareMe


1 Answers

EDIT

Sorry, your question clearly asked for exactly two decimal places. This is what you want:

var r = /^\$?[0-9]+(\.[0-9][0-9])?$/;

console.log(r.test("12.55"));  //true
console.log(r.test("$12.55"));  //true
console.log(r.test("$12"));     //true

console.log(r.test("$12."));    //false
console.log(r.test("$12.2"));    //false
console.log(r.test("$$12"));     //false
console.log(r.test("$12.555")); //false

You have to escape your dollar sign, then you want two option digits after the decimal point:

var r = /^\$?[0-9]+\.?[0-9]?[0-9]?$/;

console.log(r.test("12.55"));  //true
console.log(r.test("$12.55"));  //true
console.log(r.test("$12."));    //true
console.log(r.test("$12"));     //true

console.log(r.test("$$12"));     //false
console.log(r.test("$12.555")); //false

Fiddle

Or, to allow arbitrary digits after the decimal point, you could use a Kleene closure instead of two optional digits

var r = /^\$?[0-9]+\.?[0-9]*$/;

console.log(r.test("12.55"));  //true
console.log(r.test("$12.55"));  //true
console.log(r.test("$12."));    //true
console.log(r.test("$12"));     //true
console.log(r.test("$12.555")); //true

console.log(r.test("$$12"));     //false
like image 68
Adam Rackis Avatar answered Oct 08 '22 12:10

Adam Rackis