The most powerful data validation library for JS

Overview
Comments
  • Really custom messages are impossible

    Really custom messages are impossible

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

    feature 
    opened by ivan-kleshnin 48
  • Remove required flags for all elements

    Remove required flags for all elements

    Hello!

    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

    support 
    opened by SzaboAdamImre 35
  • Joi.string().optional() doesn't treat an empty string as unset

    Joi.string().optional() doesn't treat an empty string as unset

    I'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?

    support 
    opened by ThisIsMissEm 33
  • Using joi on the client

    Using joi on the client

    Is 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 support 
    opened by qzg 31
  • Recursive schema (tree-like) validation

    Recursive schema (tree-like) validation

    Hello,

    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 ?

    feature 
    opened by Marsup 30
  • Optional between dates with allow('')

    Optional between dates with allow('')

    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 
    opened by ugate 28
  • Painful defaults

    Painful defaults

    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:

    • [ ] empty strings not being valid
    • [x] ~stripUnknown stripping arrays (does anyone even use that ?)~ Done in v14.
    • [x] most people expect minDomainAtoms: 2 in string().email() apparently, should it change?

    Anything else ?

    support 
    opened by Marsup 27
  • Leaving @hapi and making new plans

    Leaving @hapi and making new plans

    TL;DR

    Replace @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.

    Background

    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:

    • https://github.com/hapijs/hapi/issues/4111
    • https://github.com/hapijs/hapi/issues/4113
    • https://github.com/hapijs/hapi/issues/4114

    Organization Changes

    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.

    Relationship to hapi

    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.

    Near Future

    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.

    Future plans

    I have big plans for joi, including a new fresh focus on client side development, size, and performance. Some things to expect:

    • a completely modular architecture allowing you to grab just the rules you need
    • validation levels to keep validation light on the client and heavier on the server
    • consistent language support across all rules
    • native TypeScript support

    Commercial support

    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 changes 
    opened by hueniverse 26
  • How can check the options key here?

    How can check the options key here?

    Context

    • node version:v8.9.1
    • joi version:13.1.2
    • environment (node, browser): Visual studio code
    • used with (hapi, standalone, ...):standalone
    • any other relevant information:

    What are you trying to achieve or the steps to reproduce ?

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

    Which result you had ?

    Not able to identify the condition to achieve the below result

    What did you expect ?

    If 'maxSimilarFonts' is present in the schema then 'options' key must contain 'SIMILARITY' string. Any help is appreciated.

    support 
    opened by amitdhawan 26
  • Date enhancements and support for Unix Timestamps

    Date enhancements and support for Unix Timestamps

    Revised

    This PR includes the following changes:

    • Support for decimals in date() validation
    • New constraint for date.timestamp() that supports both javascript and unix timestamps
    • Updated Tests, API documentation, and added date example

    Note: 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 feature 
    opened by galenandrew 25
  • array().single()

    array().single()

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

    feature 
    opened by hueniverse 25
  • should change ValidationError class from anonymous class to named class

    should change ValidationError class from anonymous class to named class

    Support plan

    • is this issue currently blocking your project? (yes/no): NO
    • is this issue affecting a production system? (yes/no): NO

    Context

    • node version: 19.1.0
    • module version: 17.7.0
    • environment (e.g. node, browser, native): node
    • used with (e.g. hapi application, another framework, standalone, ...): another framework
    • any other relevant information:

    What problem are you trying to solve?

    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]
    

    Do you have a new or modified API suggestion to solve the problem?

    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 
    opened by leandroluk 0
  • Doesn't work with create-react-app

    Doesn't work with create-react-app

    Support plan

    • is this issue currently blocking your project? (yes/no): yes
    • is this issue affecting a production system? (yes/no): no

    Context

    • node version: N/A
    • module version with issue: 17.7.0
    • last module version without issue:
    • environment (e.g. node, browser, native): browser
    • used with (e.g. hapi application, another framework, standalone, ...): latest create-react-app
    • any other relevant information:

    What are you trying to achieve or the steps to reproduce?

    npx create-react-app test
    cd test
    npm i joi
    

    Add this to top of index.js:

    import Joi from 'Joi';
    
    npm run start
    

    What was the result you got?

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

    What result did you expect?

    Joi should import correctly, without error.

    support 
    opened by OneHatRepo 0
  • Support for any.fork() for array objects

    Support for any.fork() for array objects

    Support plan

    • is this issue currently blocking your project? (yes/no): YES
    • is this issue affecting a production system? (yes/no): NO

    Context

    • node version: 16.13.1
    • module version: 17.7.0
    • environment (e.g. node, browser, native): node
    • used with (e.g. hapi application, another framework, standalone, ...): standalone
    • any other relevant information:

    How can we help?

    I'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 
    opened by cshuiu 4
  • Validate the validation: Disallow certain feature/combinations

    Validate the validation: Disallow certain feature/combinations

    Support plan

    • is this issue currently blocking your project? (yes/no): no
    • is this issue affecting a production system? (yes/no): no

    Context

    • node version: 14.21.1
    • module version: 17.6.1
    • environment (e.g. node, browser, native): node
    • used with (e.g. hapi application, another framework, standalone, ...): express
    • any other relevant information:

    How can we help?

    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:

    • The usage of Joi.any()
    • The usage of Joi.object without further narrowing down (by .keys, .pattern etc.)
    • The usage of Joi.array withouth items etc.
    • The usage of Joi.string() without narrowing down (.email() , regex etc)

    Is that possible somehow?

    support 
    opened by christian-schwaderer 0
  • Difficulties when importing, ... is not a function

    Difficulties when importing, ... is not a function

    Support plan

    • is this issue currently blocking your project? (yes/no): no
    • is this issue affecting a production system? (yes/no): no

    Context

    • node version: 18.12.1
    • module version with issue: 17.7.0
    • last module version without issue: idk
    • environment (e.g. node, browser, native): node, typescript
    • used with (e.g. hapi application, another framework, standalone, ...): nest, jest
    • any other relevant information:

    What are you trying to achieve or the steps to reproduce?

    Using

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

    What was the result you got?

    see above

    What result did you expect?

    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

    support 
    opened by sezanzeb 0
Owner
Sideway Inc.
Sideway Inc.
Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ·

Dataffy 14 Oct 27, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
A simple credit cards validation library in JavaScript

creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js

ContaAzul 323 Jan 7, 2023
v8n ☑️ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
A lightweight NodeJS library for strict mime-type validation on streams

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.

CEO of Death Star 9 Apr 3, 2022
String validation

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

null 20.7k Jan 5, 2023
Cross Browser HTML5 Form Validation.

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

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

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

Cedric Dugas 2.6k Dec 23, 2022
Dead simple Object schema validation

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

Jason Quense 19.2k Jan 2, 2023
Schema-Inspector is an JSON API sanitisation and validation module.

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

null 494 Oct 3, 2022
:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Netto Farah 160 Dec 14, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
📫 Offline email validation - JS or TS

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]')

earnifi 12 Dec 25, 2022
TypeScript-first schema validation for h3 and Nuxt applications

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

Robert Soriano 48 Dec 28, 2022
Schema validation utilities for h3, using typebox & ajv

h3-typebox JSON schema validation for h3, using typebox & ajv. Install # Using npm npm install h3-typebox # Using yarn yarn install h3-typebox # Usi

Kevin Marrec 43 Dec 10, 2022