diff --git a/lib/serializer.js b/lib/serializer.js index 0bd2bc5c..ea810293 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -50,17 +50,14 @@ module.exports = class Serializer { } asNumber (i) { - if (typeof i !== 'number') { - i = Number(i) - } - // NaN !== NaN - if (i !== i) { // eslint-disable-line no-self-compare + const num = Number(i) + if (Number.isNaN(num)) { throw new Error(`The value "${i}" cannot be converted to a number.`) + } else if (!Number.isFinite(num)) { + return null + } else { + return '' + num } - if (i === Infinity || i === -Infinity) { - return 'null' - } - return '' + i } asBoolean (bool) { diff --git a/test/fix-604.test.js b/test/fix-604.test.js new file mode 100644 index 00000000..ce8c3685 --- /dev/null +++ b/test/fix-604.test.js @@ -0,0 +1,24 @@ +'use strict' + +const t = require('tap') +const fjs = require('..') +const schema = { + type: 'object', + properties: { + fullName: { type: 'string' }, + phone: { type: 'number' } + } +} + +const input = { + fullName: 'Jone', + phone: 'phone' +} + +const render = fjs(schema) + +try { + render(input) +} catch (err) { + t.equal(err.message, 'The value "phone" cannot be converted to a number.') +}