Hapi/Joi Validation For Number Fails

2019-08-31 02:15发布

问题:

I am trying to validate number value which will include integer as well as float values. Following is my implementation for the same.

Joi Schema.

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)
})

Object

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: child "v2" fails because ["v2" must be a number]

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.

Is there any way by which we can convert this value to 13.0

回答1:

You can use a regex in order to match numbers with a dot, for instance:

Joi.string().regex(/\d{1,2}[\,\.]{1}/)

And then combine both validations using Joi.alternatives:

Joi.alternatives().try([
      Joi.number().empty("").allow(null),
      Joi.string().regex(/\d{1,2}[\,\.]{1}/)
])

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.

If you want to know more about the regex used in the example, you can test it in here: https://regexr.com/