Archive | December, 2009

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)");

Comments { 6 }