v8n ☑️ ultimate JavaScript validation library

Overview

v8n

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

CircleCI npm version npm bundle size (minified + gzip)

Installation - Documentation - API

Buy Me A Coffee

Introducing v8n

v8n is an acronym for validation. Notice that it has exactly eight letters between v and n in the "validation" word. This is the same pattern we are used to seeing with i18n, a11y, l10n ...

Chainable API

Create validations very easily with its chainable API:

v8n()
  .string()
  .minLength(5)
  .first("H")
  .last("o")
  .test("Hello"); // true

Incredibly fluent

Mix rules and modifiers together to create complex validations with great ease and fluency:

v8n()
  .array()
  .every.number()
  .not.some.negative()
  .test([1, 2, -3]); // false - no negative please!

So fluent that it looks like English:

v8n()
  .some.not.uppercase() // expects that some character is not uppercase
  .test("Hello"); // true

v8n()
  .not.some.uppercase() // expects that no character is uppercase
  .test("Hello"); // false

Notice how we made very different validation strategies just by changing the order of the modifiers. It's so intuitive that seems to be impossible, but this is v8n.

Customizable

Create your own custom validation rules in a very intuitive way:

function foo() {
  return value => value === "bar";
}

v8n.extend({ foo });

v8n will treat them like built-in ones:

v8n()
  .string()
  .foo()
  .test("bar"); // true

Reusable

Export validations just like you're used to do with your JavaScript modules:

specialNumber.js

import v8n from "v8n";

export default v8n()
  .number()
  .between(50, 100)
  .not.even();

and use them anywhere you want:

import specialNumber from "../specialNumber";

specialNumber.test(63); // true

For any kind of data

Use v8n to validate your data regardless of its type. You can validate primitives, arrays, objects and whatever you want! You can also use them together!

// numbers
v8n()
  .number()
  .between(5, 10)
  .test(7); //true

// strings
v8n()
  .string()
  .minLength(3)
  .test("foo"); // true

// arrays
v8n()
  .array()
  .every.even()
  .test([2, 4, 6]); // true

// objects
const myData = { id: "fe03" };

v8n()
  .schema({
    id: v8n().string()
  })
  .test(myData); // true

For any kind of validation

Do simple validations with boolean based tests. Get more information about your validation process with exception based tests. And of course, perform asynchronous tests as well. All in one library.

Boolean based validation:

v8n()
  .string()
  .first("H")
  .test("Hello"); // true

Exception based validation:

try {
  v8n()
    .string()
    .first("b")
    .check("foo");
} catch (ex) {
  console.log(ex.rule.name); // first
}

Getting all failures:

const failed = v8n()
  .string()
  .minLength(3)
  .testAll(10);

failed;
// [
//   ValidationError { rule: { name: "string", ... } },
//   ValidationError { rule: { name: "minLength", ... } }
// ]

Async validation:

If your validation strategy has some rule that performs time consuming validation, like a back-end check, you should use asynchronous validation:

{ /* valid! */ }) .catch(ex => { /* invalid! */ });">
v8n()
  .somAsyncRule()
  .testAsync("foo") // returns a Promise
  .then(result => {
    /* valid! */
  })
  .catch(ex => {
    /* invalid! */
  });

Shareable

Share your rules with the world, and use theirs as well.

Create useful validation rules and share them with the open source community, and let people around the world validate without reinventing the wheel.

Ready to use!

There are a lot of built-in rules and modifiers for you to use already implemented in v8n's core. Take a look at all of them in our API page. But if you can't find what you need, go ahead and make it.

Tiny!

All these incredible features for just a few bytes:

npm bundle size (minified + gzip)

Architecture

The v8n core is composed of rules and modifiers. They are used together to build complex validations in an easy way.

Rules

Rules are the heart of the v8n ecosystem. You use them to build your validation strategies:

v8n()
  .string()
  .minLength(3)
  .test("Hello"); // true

In this code snippet, we're using two rules (string and minLength) to build our validation strategy. So our validated value ("Hello") is valid because it's a string and it is at least 3 characters long.

Rules can be more powerful if used along with modifiers. Learn about them in the next section.

Modifiers

Modifiers can be used to change rules meaning. For example, you can use the not modifier to expect the reversed result from a rule:

v8n()
  .not.equal(5)
  .test(5); // false

You can check all available modifiers on our documentation page.

Modifiers are very powerful. They work as decorators for rules. When used together, they allow you to build very complex validations.

Contribute

Contributions of any kind are welcome! Read our CONTRIBUTING guide.

License

MIT License

Comments
  • Add 'some' and 'every' as additional modifiers

    Add 'some' and 'every' as additional modifiers

    Proposing to add some and every as new modifiers for testing array elements.

    v8n()
      .some.number()
      .even()
      .test([1, 2, 3]); // true
    
    v8n()
      .some.number()
      .even()
      .test([1, 3]); // false
    
    v8n()
      .every.number()
      .even()
      .test([1, 2, 3]); // false
    
    v8n()
      .every.number()
      .even()
      .test([2, 4]); // true
    

    An argument can be made for the following instead:

    [1, 2, 3].some(i => v8n().number().even(i));
    

    But personally, I find the former more elegant.

    p.s. I can work on this feature request.

    Status: Pending Type: Change Scope: API Note: Help Wanted 
    opened by adityasharat 17
  • Add untranspiled build and typescript support

    Add untranspiled build and typescript support

    Description

    This pull request adds a single build that completely untranspiled called v8n.esm.browser.js. This build can be used for modern browsers where backward compatibility is no needed. It also adds typescript typings that allow usage of this package in a typescript environment.

    Fixes #165 Fixes #28 Fixes #180

    Type of change

    • [x] New feature (non-breaking change which adds functionality)

    Checklist:

    • [x] I have created my branch from a recent version of master
    • [x] The code is clean and easy to understand
    • [x] I have added changes to the Unreleased section of the CHANGELOG
    Scope: API Scope: Build Type: Enhancement Status: Completed 
    opened by sbarfurth 15
  • Schema testing against an object that extends the schema

    Schema testing against an object that extends the schema

    Hi, thanks for this lib, I just started using it and it's a joy (no pun^^).

    I may have missed something in the docs, but is testing an object extending the schema supposed to return true?

    const validation = v8n().schema({
      id: v8n()
        .number()
        .positive(),
      name: v8n()
        .string()
        .minLength(4)
    });
    
    validation.test({
      id: 1,
      name: "Luke"
    }); // true
    
    validation.test({
      id: 1,
      name: "Luke",
      lastname: "Skywalker"
    }); // also true?
    

    If so, maybe it would be great to add it in the docs?

    Type: Question Scope: Rule Status: Pending 
    opened by dbismut 10
  • Add

    Add "any" rule for branching validations

    This is a preliminary implementation and should be validated yet.

    We have to make some decisions like what we should expect when no validation is given. Should we get a valid or invalid result?

    In the current implementation, I decided to make the arguments spread to an array (... validations) instead of getting an array directly. What do you think about?

    And this PR closes #53.

    Scope: Rule Status: Completed 
    opened by imbrn 10
  • Test for valid numbers

    Test for valid numbers

    Unfortunately v8n().number().test(NaN) returns true, which while technically correct according to JavaScript is usually not what you want.

    A few options:

    • Have number return false for NaN.
    • Have another not.nan() check.
    • Have a finite() check which returns false for NaN, Infinity, and -Infinity.
    Type: Feature Request good first issue Scope: Rule Status: In Progress 
    opened by iangilman 10
  • fix: proxy-less env support

    fix: proxy-less env support

    Description

    Commit picked from https://github.com/bassarisse/v8n/ and applied to the most recent version of the library. Provides IE11 support.

    Type of change

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] Other (please, feel free to specify what kind of change it is)

    Checklist:

    • [x] I have created my branch from a recent version of master
    • [x] The code is clean and easy to understand
    • [ ] I have written tests to guarantee that everything is working properly
    • [ ] I have made corresponding changes to the documentation
    • [ ] I have added changes to the Unreleased section of the CHANGELOG
    Type: Enhancement Status: Abandoned 
    opened by NoemiRozpara 9
  • Include string holding a number in examples

    Include string holding a number in examples

    Wonderful library, thank you.

    I had a poke around but didn't find anything for this. A common use case for this library is probably validating user input that comes in the form of strings.

    v8n().number().test('23')
    v8n().integer().test('23')
    

    are both rightly false. But what's the appropriate way to test if a string contains a number/integer? It feels wrong to add a pre-validation validation step where we attempt to convert to an int and handle as a validation failure if it doesn't. But perhaps that's the intended usage. Or maybe I just missed it.

    Thanks!

    Type: Question 
    opened by bakert 8
  • Support for Async Validations

    Support for Async Validations

    This looks like a really nice tool, however I don't see any support or documentation on async/promise-based validation.

    Is this something that this project plans on supporting or is this outside of the plan? Classic use-case being username validation, for example!

    Type: Feature Request Status: Pending Priority: High 
    opened by andrewhathaway 8
  • Manually deploy dispatching for GH Actions

    Manually deploy dispatching for GH Actions

    Description

    Adds a Github Action workflow trigger that permits manually deploy dispatching (npm publish).

    https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch

    Type of change

    • [x] Other (please, feel free to specify what kind of change it is)

    Checklist:

    • [x] I have created my branch from a recent version of master
    Priority: High Status: In Progress 
    opened by imbrn 7
  • Pass

    Pass "optional" rule with 0 length strings

    Would be great if the optional rule would also pass on an empty trimmed string. Guessing there might be a more technical reason as to why you chose not add in, but figured I'd bring it up just in case.

    Type: Feature Request Scope: Rule 
    opened by chasegiunta 7
  • Create a process for pull requests

    Create a process for pull requests

    There should be a defined process for new features. I believe a good starting point would be a pull request template containing a checklist for all important tasks when changing something.

    The main points should be:

    - [ ] Tests are passing
    - [ ] The code is properly formatted with Prettier
    - [ ] The code is commented or easily understandable
    - [ ] Changes are documented
    - [ ] Changes are added to the `Unreleased` section within the changelog
    

    Can you think of additional points or change any? What else should be in the template?

    Note: Needs Discussion Type: Maintenance 
    opened by sbarfurth 7
  • Improve schema rule with dependent validations and strict mode

    Improve schema rule with dependent validations and strict mode

    As discussed in other issues the schema rule should ideally support:

    • [ ] conditional validations depending on other properties in the schema (#164)
    • [x] strict mode that validates if a schema matches exactly without extraneous properties (#179)
    Scope: Rule Status: Pending Type: Enhancement 
    opened by sbarfurth 0
  • Improve support for CI/CD

    Improve support for CI/CD

    Problem: Nowadays, we have to execute the library deployment process every time we need to produce a new version.

    It would be nice to have a complete CI/CD process, where every new merge on the main branch would produce an automatic deployment.

    Maybe we should adhere to the semantic-release project for helping us to achieve a commit-based versioning system. :thinking:

    Scope: Build Status: Accepted Type: Enhancement 
    opened by imbrn 2
Releases(v1.5.1)
Owner
Bruno C. Couto
Software Engineer by profession, Christian by election.
Bruno C. Couto
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
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
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
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
The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Sideway Inc. 19.6k Jan 4, 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 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
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
: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
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
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