Skip to content

Instantly share code, notes, and snippets.

@jonkemp
Last active June 8, 2023 17:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jonkemp/9094324 to your computer and use it in GitHub Desktop.
Save jonkemp/9094324 to your computer and use it in GitHub Desktop.
Currency validation method for the jQuery Validation plugin. Decimal place is optional but if included, it requires 2 places. Also, the dollar sign is optional.
// Validation method for US currency
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
@pamanes
Copy link

pamanes commented Sep 19, 2014

nice!

@Jrizzi1
Copy link

Jrizzi1 commented Apr 22, 2015

it doesnt seem that the dollar sign is optional, it wont accept a value from me without it

@lksedor
Copy link

lksedor commented Feb 24, 2016

@Jrizzi1 - Try removing the ^$ from the regex - it should work then without the $ sign

If you want to have the $ as an optional element, add a ? after the ^$

@Sharuru
Copy link

Sharuru commented Apr 1, 2016

Nice work, thanks 😄

@rvpatel
Copy link

rvpatel commented May 9, 2019

How to fix min and max as well?

@Mechular
Copy link

How to fix min and max as well?
@rvpatel
You can add those to the rule:
https://jqueryvalidation.org/min-method/
https://jqueryvalidation.org/max-method/

@jsharf-firstam
Copy link

Excellent work.
However, if I type a letter into the field by mistake, and then tab out to the next field, it fills the current field with "NaN" in addition to displaying the error message. Is there a way to keep the NaN from showing up in the text field?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment