diff --git a/src/additional/currency.js b/src/additional/currency.js new file mode 100644 index 000000000..45e9a728c --- /dev/null +++ b/src/additional/currency.js @@ -0,0 +1,41 @@ +/** + * Validates currencies with any given symbols by @jameslouiz + * Symbols can be optional or required. Symbols required by default + * + * Usage examples: + * currency: ['£', false] - Use false for soft currency validation + * currency: ['$', false] + * currency: ['RM', false] - also works with text based symbols such as 'RM' - Malaysia Ringgit etc + * + * + * + * Soft symbol checking + * currencyInput: { + * currency: ['$', false] + * } + * + * Strict symbol checking (default) + * currencyInput: { + * currency: '$' + * //OR + * currency: ['$', true] + * } + * + * Multiple Symbols + * currencyInput: { + * currency: '$,£,¢' + * } + */ +jQuery.validator.addMethod('currency', function(value, element, param) { + var paramType = typeof param === 'string', + symbol = paramType ? param : param[0], + soft = paramType ? true : param[1], + regex; + + symbol = symbol.replace(/,/g, ''); + symbol = soft ? symbol + ']' : symbol + ']?'; + regex = '^[' + symbol + '([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$'; + regex = new RegExp(regex); + return this.optional(element) || regex.test(value); + +}, 'Please specify a valid currency'); diff --git a/test/methods.js b/test/methods.js index e324bb325..5d0a26742 100644 --- a/test/methods.js +++ b/test/methods.js @@ -1166,4 +1166,28 @@ test("rangeWords", function(){ ok(!method( "
But you can “count” me as too long
", rangeWords), "Too many words with smartquotes w/ HTML"); }); +test("currency", function() { // Works with any symbol + var method = methodTest( "currency" ); + ok( method( "£9", '£'), "Valid currency" ); + ok( method( "£9.9", '£'), "Valid currency" ); + ok( method( "£9.99", '£'), "Valid currency" ); + ok( method( "£9.90", '£'), "Valid currency" ); + ok( method( "£9,999.9", '£'), "Valid currency" ); + ok( method( "£9,999.99", '£'), "Valid currency" ); + ok( method( "£9,999,999.9", '£'), "Valid currency" ); + ok( method( "9", ['£', false]), "Valid currency" ); + ok( method( "9.9", ['£', false]), "Valid currency" ); + ok( method( "9.99", ['£', false]), "Valid currency" ); + ok( method( "9.90", ['£', false]), "Valid currency" ); + ok( method( "9,999.9", ['£', false]), "Valid currency" ); + ok( method( "9,999.99", ['£', false]), "Valid currency" ); + ok( method( "9,999,999.9", ['£', false]), "Valid currency" ); + ok(!method( "9,", '£'), "Invalid currency" ); + ok(!method( "9,99.99", '£'), "Invalid currency" ); + ok(!method( "9,", '£'), "Invalid currency" ); + ok(!method( "9.999", '£'), "Invalid currency" ); + ok(!method( "9.999", '£'), "Invalid currency" ); + ok(!method( "9.99,9", '£'), "Invalid currency" ); +}); + })(jQuery);