diff --git a/src/lib/isFloat.js b/src/lib/isFloat.js index 84bdc782c..3856d70a1 100644 --- a/src/lib/isFloat.js +++ b/src/lib/isFloat.js @@ -5,7 +5,14 @@ import { decimal } from './alpha'; export default function isFloat(str, options) { assertString(str); options = options || {}; - const float = new RegExp(`^(?:[-+])?(?:[0-9]+)?(?:\\${options.locale ? decimal[options.locale] : '.'}[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$`); + // Fall back to `.` unless the locale is an own key of `decimal`. Indexing + // `decimal[options.locale]` directly would also match inherited names such as + // `__proto__`, `constructor` or `toString`, whose truthy values leak into the + // pattern (e.g. the separator becomes the literal `[object Object]`). + const decimalSeparator = Object.prototype.hasOwnProperty.call(decimal, options.locale) + ? decimal[options.locale] + : '.'; + const float = new RegExp(`^(?:[-+])?(?:[0-9]+)?(?:\\${decimalSeparator}[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$`); if (str === '' || str === '.' || str === ',' || str === '-' || str === '+') { return false; } diff --git a/test/validators.test.js b/test/validators.test.js index 98d2a12ff..b1f8f8400 100644 --- a/test/validators.test.js +++ b/test/validators.test.js @@ -4857,6 +4857,42 @@ describe('Validators', () => { 'foo', ], }); + test({ + validator: 'isFloat', + args: [{ + locale: 'is-NOT-a-locale', + }], + valid: [ + '123', + '123.123', + '-3.5e2', + ], + invalid: [ + '3undefined5', + '123,123', + 'foo', + '', + ], + }); + // Inherited property names (e.g. __proto__, constructor) are not own keys of + // the decimal map, so they must fall back to the "." separator too. + for (const inheritedLocale of ['__proto__', 'constructor', 'toString', 'hasOwnProperty', 'valueOf']) { + test({ + validator: 'isFloat', + args: [{ locale: inheritedLocale }], + valid: [ + '123', + '123.123', + '-3.5e2', + ], + invalid: [ + '123,123', + '3[object Object]5', + 'foo', + '', + ], + }); + } test({ validator: 'isFloat', args: [{