Hapi/Joi验证数字失败 [英] Hapi/Joi Validation For Number Fails
问题描述
我正在尝试验证数字值,该值将包括整数以及浮点值.以下是我的实现方法.
I am trying to validate number value which will include integer as well as float values. Following is my implementation for the same.
Joi模式.
const numcheckschema = Joi.object().keys({
v1:Joi.number().empty("").allow(null).default(99999),
v2:Joi.number().empty("").allow(null).default(99999),
v3:Joi.number().empty("").allow(null).default(99999)
})
对象
objnum={
v1:"15",
v2:"13.",
v3:"15"
}
objValidated = Joi.validate(objnum, numcheckschema);
console.log(objValidated);
执行上述代码时出现错误
When i execute the above mentioned code I get an error
ValidationError:子级"v2"失败,因为["v2"必须是数字]
ValidationError: child "v2" fails because ["v2" must be a number]
根据文档,当我们尝试将任何数字值作为字符串传递时,它将值转换为数字,但是在这种情况下,我的值为 13 .它无法转换为数字并引发错误.
as per the documentation when we tries to pass any numeric value as a string it converts the values to number but here in this case my value is 13. which is not able to convert into number and throwing an error.
是否可以通过任何方式将此值转换为 13.0
Is there any way by which we can convert this value to 13.0
推荐答案
您可以使用正则表达式将数字与点匹配,例如:
You can use a regex in order to match numbers with a dot, for instance:
Joi.string().regex(/\d{1,2}[\,\.]{1}/)
然后使用 Joi.alternatives :
Joi.alternatives().try([
Joi.number().empty("").allow(null),
Joi.string().regex(/\d{1,2}[\,\.]{1}/)
])
但是,我认为您可能需要使用 Number(字符串值)将有效负载转换为数字.您需要检查有效载荷类型,如果不是数字,则需要对其进行转换.
However, I think you may need to convert the payload to number using Number(string value). You need to check the payload type, if it isn't a Number, you need to convert it.
如果您想了解示例中使用的正则表达式的更多信息,可以在此处进行测试: https://regexr .com/
If you want to know more about the regex used in the example, you can test it in here: https://regexr.com/
这篇关于Hapi/Joi验证数字失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!