简体   繁体   中英

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM