'jQuery Validate money field, accept spaces?

I have a custom validator for money fields, it accepts values like

12,00$
122.04$
12123123

Now, I want to make it accept theese values:

1 200$
1 200,22$

So accept spaces. And unfortunately, I'm not very good at regex.

Here's my custom validator:

$.validator.addMethod("money", function(value, element) {
    return this.optional(element) || value.match(/^\$?(\d+(?:[\.\,]\d{1,2})?)\s?\$?$/);
}, "Not valid...");


Solution 1:[1]

You can use this regex:

^\$?(\d+(?:\s\d+)*(?:[\.\,]\d{1,2})?)\s?\$?$

I have only added (?:\s\d+)* to your regex to allow any number of digits with spaces after an initial number. Mind you do not have to escape . and , inside the character class [\.\,] (it is equal to [.,]).

Here is a demo.

Try

$.validator.addMethod("money", function(value, element) {
    return this.optional(element) || value.match(/^\$?(\d+(?:\s\d+)*(?:[.,]\d{1,2})?)\s?\$?$/);
}, "Not valid...");

Solution 2:[2]

You could use the below regex.

^\$?\d+(?:[ ,]\d+)*(?:\.\d+)?\$?$

DEMO

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Avinash Raj