Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/lib/isFloat.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
36 changes: 36 additions & 0 deletions test/validators.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: [{
Expand Down
Loading