Reputation: 545
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...");
Upvotes: 0
Views: 127
Reputation: 626903
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...");
Upvotes: 1
Reputation: 174706
You could use the below regex.
^\$?\d+(?:[ ,]\d+)*(?:\.\d+)?\$?$
Upvotes: 1