From ab3f5f4cb608c58fd0f31ce84ad69d2cde6a6f31 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Wed, 30 Nov 2016 12:10:38 -0500 Subject: [PATCH] Validate correct Number format * src/validate/formatter/Number.js (parse): Validate number format. * test/validate/formatter/NumberTest.js: Modify accordingly. --- src/validate/formatter/Number.js | 12 ++++++++++-- test/validate/formatter/NumberTest.js | 8 ++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/validate/formatter/Number.js b/src/validate/formatter/Number.js index 07afc0d..19240bc 100644 --- a/src/validate/formatter/Number.js +++ b/src/validate/formatter/Number.js @@ -109,11 +109,19 @@ module.exports = Trait( 'Number' ) * @param {string} data data to parse * * @return {string} data formatted for storage + * + * @throws Error if number is not of a valid format */ 'virtual abstract override public parse': function( data ) { - var cleaned = this.__super( data ).replace( /[ ,]/g, '' ), - parts = this.split( cleaned ); + var cleaned = this.__super( data ).replace( /[ ,]/g, '' ); + + if ( !/^[0-9]*(\.[0-9]*)?$/.test( cleaned ) ) + { + throw Error( "Invalid number: " + data ); + } + + var parts = this.split( cleaned ); return parts.integer + this.scale( parts.significand, this._scale ); }, diff --git a/test/validate/formatter/NumberTest.js b/test/validate/formatter/NumberTest.js index 7945b70..0e036d8 100644 --- a/test/validate/formatter/NumberTest.js +++ b/test/validate/formatter/NumberTest.js @@ -42,6 +42,10 @@ describe( 'validate.formatter.Number', function() // strip decimals "1.234": [ "1", "1" ], " 1, ,.": [ "1", "1" ], + + // non-numbers + "foo": false, + "123foo": false, } ); @@ -62,6 +66,10 @@ describe( 'validate.formatter.Number', function() "12,345": [ "12345.000", "12,345.000" ], " 1, ,.": [ "1.000", "1.000" ], + + // non-numbers + "1.foo": false, + "123foo.012": false, } );