joi
The most powerful schema description language and data validator for JavaScript.
Installation
npm install joi
npm install joi
I want to stick "Passwords don't match" message to verifyPassword
field.
First attempt:
verifyPassword: Joi.any().valid(Joi.ref('password')).options({language: {any: {allowOnly: "Passwords don't match"}}})
Failed. Result is "verifyPassword Passwords don't match". Joi prefixes message with label
and it seems there is no way to turn it off.
Second attempt:
verifyPassword: Joi.any().valid(Joi.ref('password')).options({language: {any: {allowOnly: "Passwords don't match"}}}).label('')
Failed. "smart" check inside Joi prohibits empty labels...
featureHello!
Is there a way to override the validation of required flags? Use-case: I have a Joi structure, where some of the properties are marked with required(). I use this Joi structure for creating, etc... of objects, where they work good.
But I have a method where only a set of the properties are required (partial update method, to be precise) - I want to disable the required property check for this method, while all other validations still remain intact.
Is it (or will it be) possible to do this?
Thx
supportI'm hitting into this when creating Joi schemas for forms, where I have a text input which can optionally be filled in, but if it's not, then no problems.
At the moment I have to use the work around of:
Joi.string().valid('').optional() // followed by any other validations
This is due to this line: https://github.com/hapijs/joi/blob/master/lib/string.js#L19
I'd be inclined to argue that if you've just said Joi.string()
without any optional or required tags, then an empty string is actually a valid value. If you say it's required, then an empty string would be invalid.
Thoughts?
supportIs there a way that I can get the Joi goodness on the client side? Maybe some other similar library of which you know? I'd like to be able to apply some of my validations on the client before hitting the server. Then, on the server I would use the exact same code to re-validate.
Any suggestions?
feature supportHello,
I'm wondering what's the best way to accomplish recursive schema validation.
Let's say I have an object that contains a property "children" holding an array of objects of the same kind.
The only way I see is to create the 1st layer of validation to get a joi object without "children", then call .keys
again on it like schema = schema.keys({ children: Joi.array().includes(schema) })
but that only gets me to validate the 1st level, not recursively.
Any tips ?
Is it possible to validate between two dates that are optional?
var schema = Joi.object().keys({
fromDate: Joi.date().max(Joi.ref('toDate')).allow(''),
toDate: Joi.date().min(Joi.ref('fromDate')).allow('')
});
Joi.validate({ fromDate: new Date(), toDate: '' }, schema, function (err, value) {
if (err) console.error(err);
console.dir(value);
});
prints out to the console:
{ [ValidationError: child "fromDate" fails because ["fromDate" references "toDate" which is not a date]]
name: 'ValidationError',
details:
[ { message: '"fromDate" references "toDate" which is not a date',
path: 'fromDate',
type: 'date.ref',
context: [Object] } ],
_object:
{ fromDate: Sat Oct 24 2015 20:31:20 GMT-0400 (Eastern Daylight Time),
toDate: '' },
annotate: [Function] }
support
Hi people!
I'm trying to create a list of the painful defaults that you would like to see disappear in the next breaking release, so please help me if you see something I don't.
So far I have:
stripUnknown
stripping arrays (does anyone even use that ?)~ Done in v14.minDomainAtoms: 2
in string().email()
apparently, should it change?Anything else ?
supportReplace @hapi/joi
with joi
in your package.json files and your require statement. No other changes required until joi v18 is published under joi
. Expect @hapi/joi
to show deprecation warnings shortly.
The hapi project is going through a change of leadership. I have decided to step down from maintaining all hapi modules with the exception of joi.
For additional information:
The joi modules was moved on GitHub from hapijs/joi
to sideway/joi
. Sideway Inc. is my company which still provides some limited commercial hapi support. Sideway will continue to own and maintain joi moving forward.
The npm joi
module is being resurrected and the current v17.1.1 has been published there (identical to the version available on @hapi/joi
). To keep things simple, there will not be a @sideway/joi
module on npm, just plain joi
.
joi will continue to be hapi's primary data validation solution. If you have been using @hapi/joi
until now, you can safely switch over. Since hapi v19, joi is no longer exposed as an external dependency. This means that you must BYO validation module and you can simply swap @hapi/joi
with joi
.
I will continue to work with the new hapi leadership to ensure that future changes to joi will remain compatible with hapi.
In order for hapi to maintain its "no external dependencies" promise, hapi now has its own fork of joi called @hapi/validate
which is a restricted version of joi used only for internal hapi API input validations. It is not exposed and should not be used outside of hapi core.
I plan to move some of joi's internals around to decouple if further from hapi modules and dependencies. Version 17.2.0 is expected in the next few days to fix bugs and add some new features. joi will be split into smaller modules internally but will still provide the same interface under joi
.
The joi documentation is going to move from https://hapi.dev to a new site and will be linked to from its current home.
I have big plans for joi, including a new fresh focus on client side development, size, and performance. Some things to expect:
If you are using an older version of joi and cannot upgrade to v17, a commercially supported version is available. Please contact [email protected] for details.
breaking changesDescribe your issue here, include schemas and inputs you are validating if needed. if 'SIMILARITY' string is present in 'options' key then there should key 'maxSimilarFonts' present in schema. This condition im able to achieve through below schema.
Now, what im not able to achieve is that: If 'maxSimilarFonts' is present in the schema then 'options' key must contain 'SIMILARITY' string. Any help is appreciated.
function checkKeys(fileContents) {
return new Promise((resolve, reject) => {
const optionsValidator = joi.string().valid(
constants.OPTIONS.TAGS,
constants.OPTIONS.ATTRIBUTES,
constants.OPTIONS.PAIRS,
constants.OPTIONS.SIMILARITY
);
const fontObjValidator = joi.object({
path: joi.string().required(),
});
const schema = joi.object().keys({
fontInfo: joi.object().pattern(/\w+/, fontObjValidator),
options: joi.array().items(optionsValidator).min(1).unique()
.required(),
mode: joi.string().valid(
constants.MODES.SCRATCH,
constants.MODES.ADD,
constants.MODES.DELETE
).required(),
maxPairs: joi.number().integer()
.min(constants.MINPAIRS)
.max(constants.MAXPAIRS)
.when('options', {
is: joi.array().items(
joi.string()
.only(constants.OPTIONS.PAIRS).required(),
joi.string()
),
then: joi.required(),
}),
maxSimilarFonts: joi.number().integer()
.min(constants.MINSIMILARITY)
.max(constants.MAXSIMILARITY)
.when('options', {
is: joi.array().items(joi.string()
.only(constants.OPTIONS.SIMILARITY)
.required(), joi.string()),
then: joi.required(),
}),
callbackApi: joi.string().uri({
scheme: ['http',
'https',
],
}).required().description('Callback url where dcs will send the output'),
});
const result = joi.validate(JSON.parse(fileContents), schema);
if (result.error == null) {
resolve(true);
} else {
reject(result.error);
}
});
Not able to identify the condition to achieve the below result
If 'maxSimilarFonts' is present in the schema then 'options' key must contain 'SIMILARITY' string. Any help is appreciated.
supportThis PR includes the following changes:
date()
validationdate.timestamp()
that supports both javascript and unix timestampsNote: Because javascript timestamps are millisecond-based and unix timestamps are second-based, the timestamp()
constraint accepts an optional type
parameter to ensure proper date conversion for the given input value.
closes #789
bug featureA different take on #474
Allows an array value to pass if the value would be a valid array element. It conversion is enabled, turns the item into an array. Joi.array().includes(Joi.number()).single()
will match [1]
and 1
and will result in [1]
in both cases.
When you have named classes in JS, you can use the instanceof
operator to make comparisons. Currently, the ValidationError
of the joi is an anonymous class, which makes it difficult to use this feature. See:
const Joi = require('joi');
console.log(Joi.ValidationError)
// > [class (anonymous) extends Error]
It is very simple to solve this problem, it is enough that in the construction of the error the name field is defined as in the example below:
class SampleError extends Error {
constructor(message) {
super(message);
this.name = 'SampleError';
}
}
console.log(SampleError)
// > [class SampleError extends Error]
feature
npx create-react-app test
cd test
npm i joi
Add this to top of index.js:
import Joi from 'Joi';
npm run start
Compiled with problems:
ERROR in ./src/index.js 9:0-22
Module not found: Error: Cannot find file: 'joi-browser.min.js' does not match the corresponding name on disk: './node_modules/Joi/dist/joi'.
Joi should import correctly, without error.
supportI'm trying to modify the schema to use in another method to validate the body I'm sending. The body doesn't contain some attributes (like ids) that the api responds with, so I want to make them optional and validate. the fork method works fine for all types, however when I try to enter a path for an array, it says this path doesn't exist, though the validation error says that path is required.
Is there any way I could modify an attribute inside an any.array().items({}) ?
let schema = Joi.object({
id: Joi.string().required(),
a: Joi.number().required(),
b: Joi.array().items({
c: Joi.number().required(),
d: Joi.number().required()
}).required()
});
let body = { id: '2', a: 5, b: [{d: 1}] };
tempSchema = schema.fork(['id', 'b[0].c'], (schema) => schema.optional());
const { error } = Joi.compile(tempSchema).validate(body, { abortEarly: false });
console.log(error);
//This throws an error: Schema does not contain path b[0].c
tempSchema = schema.fork(['id'], (schema) => schema.optional());
const { error } = Joi.compile(tempSchema).validate(body, { abortEarly: false });
console.log(error);
//This logs error: message: '"b[0].c" is required'
support
I'm setting up a new project which is expected to get quite large. Having very strict validation from the very beginning is crucial. However, in large projects with many people working on them, things tend to get out of hand and eventually less strict validation sneaks in. Once that's the case, it's hard to make the validation strict again (I've been there). So, I was just wondering: Is there a way to automatically enforce strict validation by reducing the options/possibilities of Joi?
I was thinking of disallowing:
Joi.any()
Joi.object
without further narrowing down (by .keys
, .pattern
etc.)Joi.array
withouth items
etc.Joi.string()
without narrowing down (.email()
, regex etc)Is that possible somehow?
supportUsing
"allowSyntheticDefaultImports": false,
"esModuleInterop": true,
in tsconfig.json and
import Joi from 'joi';
causes
node_modules/joi/lib/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag
Using
"allowSyntheticDefaultImports": false,
"esModuleInterop": true,
in tsconfig.json and
import * as Joi from 'joi';
Joi.string()
causes
TypeError: Joi.string is not a function
Using
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
in tsconfig.json and
import * as Joi from 'joi';
Joi.string()
causes
TypeError: Joi.string is not a function
Using
"allowSyntheticDefaultImports": true,
"esModuleInterop": false,
in tsconfig.json and
import Joi from 'joi';
Joi.string()
works when running nest start --exec "node --experimental-specifier-resolution=node --no-warnings
(we always have to use that node option, it is not related to Joi and I didn't conduct experiments on how the Joy import behaves without it),
but jest tests fail with
● Test suite failed to run
TypeError: Cannot read properties of undefined (reading 'string')
3 | import Joi from 'joi';
4 | // import * as Joi from 'joi';
> 5 | Joi.string()
Using
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
in tsconfig.json and
import Joi from 'joi';
Joi.string()
works everywhere.
In our package.json we use "type": "module"
, I don't know if this is related to the problem.
see above
For it to work like shown in the nest js docs: https://docs.nestjs.com/techniques/configuration#schema-validation, with the * as Joi
import without having to configure anything
h5Validate (WARNING -- DEPRECATED -- ARCHIVED) Hi, I'm Eric Elliott, author of "Programming JavaScript Applications" (O'Reilly). A few years ago, I wr
Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ·
jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al
validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r
jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al
Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?
creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js
The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr
A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.
validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your
Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1
jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t
Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin
Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit
property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.
email-seems-valid An offline check to see if an email seems valid. Contains TS or JS packages for browser or Node.js emailSeemsValid('[email protected]')
h3-zod Validate h3 and Nuxt 3 requests using zod schema's. Install npm install h3-zod Usage import { createServer } from 'http' import { createApp } f
h3-typebox JSON schema validation for h3, using typebox & ajv. Install # Using npm npm install h3-typebox # Using yarn yarn install h3-typebox # Usi