Regular Expression for dollar amount validation

I’m finishing up a small project that required validating dollar amounts on web-based form fields, and luckily I was using the wonderful Validation jQuery plugin.

Although this plugin doesn’t come with an out-of-the-box dollar validator method, it’s very easy to add your own. The trick was to find an appropriate regular expression. Although Google turned up several regex examples for validating dollar inputs, none met my exact criteria (the ultimate goal being to provide users with the greatest amount of data-entry leeway):

  • Allow the user to type in the $ (or not)
  • Allow amounts less than one dollar (i.e., 0 – .99)
  • Allow an optional one or two decimal places
  • No negative dollar amounts

So this is what I came up with, and it seems to be working. Two notes: (a) this expression allows inappropriate commas, but I’m stripping those out during the server-side validations, and (b) it is used in conjunction with the max() validator function to ensure the user doesn’t enter anything that could blow up a SQL Server money column:

^\$?[0-9][0-9\,]*(\.\d{1,2})?$|^\$?[\.]([\d][\d]?)$

The final jQUery validator method:

1
2
3
4
//custom validator for money fields
jQuery.validator.addMethod("money", function(value, element) {
	return this.optional(element) || /^\$?[0-9][0-9\,]*(\.\d{1,2})?$|^\$?[\.]([\d][\d]?)$/.test(value);
}, "Please provide a valid dollar amount (up to 2 decimal places)");

,

6 Responses to Regular Expression for dollar amount validation

  1. Andrew December 31, 2009 at 4:19 am #

    Many thanks for this. Worked straight away. With 30 years in application programming it always surprises me that these issues are ‘addins’ rather than part of the ‘standard’, but this works a treat.

  2. k.anantharengan July 7, 2010 at 5:04 am #

    brilliant regular expression.keep it up.works really well

  3. Joel September 16, 2011 at 8:21 am #

    Thanks, this is exactly what I needed!!

  4. Anonymous April 4, 2013 at 3:05 pm #

    Hi,

    This is an excellent post and quite helpful. I want to add the ability to add negative numbers as well. How can I do that?
    I am not sure but users can enter “-” sign before or after the “$” sign too.

  5. Danny April 8, 2014 at 12:10 pm #

    Thanks so much! After searching and searching, trying a multitude of other code (plus hours of customizing them), yours worked without ANY need to change anything! I’m so impressed! Thanks again!

  6. WebDevJoshB May 22, 2014 at 1:06 pm #

    Thank you so much for this. I’m relatively new to jQuery; this saved me a ton of time.

    I’m so used to “liking” stuff that I looked for the button for this! :)

Leave a Reply