Delightfully simple, feature packed and customisable tool for validation and sanitization of any kind of data. Can be used on the client side as well as on the server side.
Works with React, React Native, Angular, Vue or NodeJs
Plentitude of validation methods for different data types
Many useful sanitization methods for data normalization
Typed from tail to toe for amazing developer experience
Very intuitive and easy to use
Extremely flexible and extendable
Supports sync and async logic
Encourages you to build reusable schemas
Combine multiple schemas into more complex ones
Conditionally connectschemas for complex scenarios
Write custom validation and sanitization logic with ease
Easily override error messages
Comes translated into 6 different languages (English, German, French, Italian, Spanish and Russian)
Easily add a new language or override translation
yarn add @corets/schema
npm install --save @corets/schema
Concepts
Every schema specialises on a specific data type and comes with various assertion and sanitization methods. Some methods you'll be able to find on every schema, others are exclusive to a specific kind of schema.
Assertions are used for validation purposes to ensure that a value is valid.
Check out this React form library, it has a support for schemas and changes the way you work with forms:
Quick start
Here is an example of all the available schemas and how to import them:
Schemas can be freely combined with one another. When describing arrays and objects there is no way around this. Here is an example of two schemas being combined:
You can freely define validations and sanitizers at runtime using logical links.
Logical links can be used to attach custom validation logic:
import { string } from "@corets/schema"
string().min(3).max(20)
.and(async (v) => await isUsernameTaken(v) && "Username is already taken")
Custom validations
Example of a validation function returning an error message:
import { number } from "@corets/schema"
const customValidation = (value: any) => value < 12 && "Must be bigger than 12"
number().and(customValidation)
number().or(customValidation)
number().also(customValidation)
You can also return multiple error messages at once using an array.
Example of a validation function returning a schema:
As you can see, even though the string " foo " has a length greater than 4. During the sanitization, value gets trimmed, becomes"foo" and therefore the test will fail.
Schema.sanitizeAndValidate()
Example of a successful validation with sanitizers:
{
"self": ["Must be at least \"4\" characters long"],
}
Schema.sanitizeAndVerify()
Schema.testAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.validateAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.verifyAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.sanitizeAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.sanitizeAndTestAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.sanitizeAndValidateAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.sanitizeAndVerifyAsync()
This library has no async validation or sanitization methods itself, but you can add your own.
Schema.also()
Connects multiple schemas or attaches a custom validation function to a schema. Connections made with this link are invoked regardless of the status of the parent schema. This is perfect when you try to combine multiple schemas or attach a custom validation function to a schema to make it behave like one single unit.
Logically connects multiple schemas, or a custom validation function to a schema. Schemas and validation functions connected using this link will only be executed if the parent schema validated successfully. This is a good way to connect expensive validation logic, like a database call, and make sure that it is only invoked when it's really necessary.
Logically connects multiple schemas, or a custom validation function to a schema. Schemas and validation functions connected using this link will only be executed if the parent schema validation has failed. This is useful if you want to provide an alternative validation procedure.
Provide a fallback value in case the underlying value is not a boolean:
import { boolean } from "@corets/schema"
boolean().toDefault(true)
boolean().toDefault(() => true)
date()
Contains various validators and sanitizers for dates:
import { date } from "@corets/schema"
date()
Create a schema instance without the factory function:
import { DateSchema } from "@corets/schema"
new DateSchema()
date.required()
Value must be a date:
import { date } from "@corets/schema"
date().required()
date().required(false, "Message")
date().required(() => false, () => "Message")
date.optional()
import { date } from "@corets/schema"
date().optional()
date().optional("Message")
date().optional(() => "Message")
date.equals()
Date must be equal to the given value:
import { date } from "@corets/schema"
date().equals(new Date())
date().equals(new Date(), "Message")
date().equals(() => new Date(), () => "Message")
date.after()
Underlying value must be after the given date:
import { date } from "@corets/schema"
date().after(new Date())
date().after(new Date(), "Message")
date().after(() => new Date(), () => "Message")
date.before()
Underlying value must be before the given date:
import { date } from "@corets/schema"
date().before(new Date())
date().before(new Date(), "Message")
date().before(() => new Date(), () => "Message")
date.between()
Underlying value must be between the two dates:
import { date } from "@corets/schema"
date().between(new Date(), new Date())
date().between(new Date(), new Date(), "Message")
date().between(() => new Date(), () => new Date(), () => "Message")
date.toDefault()
Provide a fallback value in case the underlying value is not a date:
import { date } from "@corets/schema"
date().toDefault(new Date())
date().toDefault(new Date(), "Message")
date().toDefault(() => new Date(), () => "Message")
array()
Contains various validators and sanitizers for arrays:
import { array, string } from "@corets/schema"
array()
Create a schema instance without the factory function:
import { ArraySchema } from "@corets/schema"
new ArraySchema()
Create an array schema with a separate schema for its children:
import { array, string } from "@corets/schema"
array(string().min(2))
There are two ways to run validations. For simple things like one-liners where you simply want to know if a value matches certain criteria, and get a true or false as result, you can use the method. For proper validation, with error messages instead of a simple true / false, you can use the method.
Sanitization methods are called before validation and are used to normalise the underlying values. For example, you can ensure that a string is capitalised and all object keys are camel-cased. Sanitization can help you reduce the number of validation errors by proactively fixing them in the first place. All sanitization methods start with the prefix to, for example: , .
Schemas can be logically linked together using methods , and . A relation will only be executed if the parent schema, that it is linked to, could validate successfully. A relation will only execute if the parent schema failed, the alternative schema will be attempted instead. A relation will execute regardless of the validation status of the parent schema.
Example of a relation, this schema will first ensure that the value is a string, and only if the first validation passes, it will test if the value is a numeric string:
Example of a relation, this schema will first check if the value is a number, and only if it's not, it will test if that value is a numeric string:
Example of an relation, this schema will execute both parts regardless of the validation outcome of the parent schema:
Methods , and do not always have to return another schema. They can be used for your custom validation functions. A custom validation function can return either another schema, a validation result, or an error message.
You can add a custom sanitizer with the method , here is an example of a sanitizer that converts everything to a string:
You can find all locales . For further examples of how to replace translations, add new languages, etc., please have a look at the docs.
This method works the same as , except it returns errors in a slightly different format. This format contains additional information about each error message and can be used for further processing of validation errors.
All sanitization methods start with the prefix to, for example: .
This method applies sanitizers on the underlying value and runs validation against the sanitized version. It returns a boolean indicating whether the value is valid, and the sanitized version of the value. Basically this calls the methods and sequentially.
All sanitization methods start with the prefix to, for example: .
This method applies sanitizers on the underlying value and runs validation against the sanitized version. It returns a validation result containing detailed error messages about why a value did not pass validation, and the sanitized version of the value. Basically this calls the methods and sequentially.
This method works exactly the same as except that it returns error messages in a different format with additional information that can be used for further processing. Take a look at to learn more about its use cases.
All sanitization methods start with the prefix to, for example: .
This is an async version of the method, that allows you to use async validators and sanitizers.
This is an async version of the method, that allows you to use async validators.
This is an async version of the method, that allows you to use async validators.
This is an async version of the method, that allows you to use async sanitizers.
This is an async version of the method, that allows you to use async validators and sanitizers.
This is an async version of the method, that allows you to use async validators and sanitizers.
This is an async version of the method, that allows you to use async validators and sanitizers.
See also for more examples.
See also and for more examples.
See also and for more examples.
See also for more examples.
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Create a new schema starting with the default value:
Value might be a string, opposite of :
Similar to , but allows dates to be equal:
Similar to , but allows dates to be equal:
Similar to , but allows dates to be equal:
Similar to , but allows times to be equal:
Similar to , but allows times to be equal:
Similar to , but allows times to be equal:
Value might be a number, opposite of :
Round value using :
Round value using :
Round value using :
Trunc value using (drops everything after the decimal point):
Value might be a boolean, opposite of :
Value might be a date, opposite of :
Value might be a array, opposite of :
You can pass a shape directly to the method too:
Value might be an object, opposite of :
You can pass a shape directly to the method too:
Allow object to contain keys that have not been configured through :
Forbid object to contain keys that have not been configured through :
Value might als be a null or undefined, opposite of :