Jay Rizzi
Jay Rizzi

Reputation: 4304

jQuery validate plugin - currency

I am attempting to figure out how to validate a number in the jQuery validate plugin as legitimate US currency, max two decimal place zeroes, without commas or dollar signs (25000.00, 1.00 , etc)

I attempted this gist https://gist.github.com/jonkemp/9094324, but it seems to require the Dollar sign ($)

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

I also attempted this Stack Overflow cliente validation using jQuery validate for currency fields but the validation code will not validate a number with two zeroes (1.00 for instance)

jQuery.validator.addMethod("currency", function(value, element) {
    var isValidMoney = /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
            return this.optional(element) || isValidMoney;
        },
        "Must be monetary (0 or 0.00)"
    );

here is the jsfiddle that is showing these issues http://jsfiddle.net/d4ywy0fu/

any help is appreciated

Upvotes: 0

Views: 7358

Answers (1)

Sparky
Sparky

Reputation: 98758

I am attempting to figure out how to validate a number in the jQuery validate plugin as legitimate US currency, max two decimal place zeroes, without commas or dollar signs (25000.00, 1.00 , etc)

Simply include the additional-methods.js file and use the built-in currency method as follows...

currency: ["$", false] // dollar sign optional

currency: "$" // dollar sign required (default)

Note: commas are optional in all cases.

DEMO: http://jsfiddle.net/d4ywy0fu/2/


NOTE: Your jsFiddle also contains a DOM ready handler inside of another DOM ready handler. While it's not harmful, it's totally superfluous.

$(function() {  // <- DOM Ready Handler

    $(document).ready(function() {  // <- DOM Ready Handler
        ....

Upvotes: 4

Related Questions