I have the following JavaScript code to test out the Hapi/Joi validation functions:
var Joi = require('joi');
var schema = { free: Joi.Types.Number().float() };
var value = { free: 3.3333 };
var err = Joi.validate(value, schema);
//err is set if value fails to validate against the schema
if (err) throw err;
The validation throws the error:
Error: the value of free must be an integer
I would like to know what I am doing wrong. I am using the current versions of Hapi and Joi.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
empty strings are not allowed by default and must be enabled with allow('') . However, if you want to specify a default value in case of empty string you have to use a different pattern: Joi. string(). empty('').
This is rather out of date now, but in case others happen on this, the syntax now is (accepting all numbers, including floats):
Joi.number();
or, if you want it to be required:
Joi.number().required();
Also, see the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With