使用 Redux-Form 时,我不明白为什么我输入的值总是作为字符串返回。我希望两个字段仅为数字

When using Redux-Form I don't understand why the value of my input is always returned as a string. I want two fields to be numbers only

我想验证我的两个名为 pricequantity 的字段正在接收一个数字类型的输入值提交表单,因此在我的验证函数中我编写了以下代码:

function validate(values) {
    const errors = {};

    _.map(FIELDS, (config, field) => {
        if (!values[field]) {
            errors[field] = `Please Enter ${config.label}`;
        }
        if (typeof values['price'] !== 'number') {
            errors['price'] = 'Please enter a number';
        }
        if (typeof values['quantity'] !== 'number') {
            errors['quantity'] = 'Please enter a number';
        }
    });

    return errors;
}

无论我是否输入数字,我的表单上都会显示错误 'Please enter a number',因此我在控制台记录了价格和数量的输入值类型,结果它们始终是字符串。我应该如何验证表格,以便检查价格和数量是否收到数字?

数据总是以字符串形式从输入字段传给您。相反,您可以使用正则表达式来查看它只包含数字而不是做

typeof values['quantity'] !== 'number'

你应该试试这样的东西

const reg = /^\d+$/;

这只会为您匹配号码。匹配此正则表达式并确定您是否有数字。

如果要匹配不带空字符串的有符号数和浮点数,请使用此正则表达式:

/^-?\d+\.?\d*$/

以下是您将如何使用它:

const numberRegex = /^-?\d+\.?\d*$/;

if (!/^\d*$/.test(value)) {
    errors['price'] = 'Please enter a number';
}
...