typic
v1.2.2
Published
Type and schema validation
Readme
Motivation
Typic is a validator for Javascript/Typescript variables and objects, very much like Hapijs's JOI. As a matter of fact JOI has been the model for Typic in many respects.
There are more object validation tools for JS than one can count, and now we have one more. The main motivation for Typic was to create a validator tool that
- returns the errors following the structure of the tested object (even for nested objects)
- returns every error (eager validation - when it makes sense)
- returns the passed values of the tested object keeping the structure
- provides tools for logical combinations (AND, NOT, OR)
Read on for a quick introduction or head to the exciting COOKBOOK or read the API description. Throughout the documentation you will find TypeScript type definitions attached to the explanations.
Usage
yarn add typicconst validator = require("typic").default;import validator from "typic";
const schema = validator()
.string()
.minLength(8)
.maxLength(64)
.hasUppercase()
.hasNumber();
const result = schema.validate("Password1");validator() // 1) creates a new Schema (an AnySchma to be precise)
.string() // 2) specifies the expected type (e.g. number, string, array, json)
.minLength(8) // 3+) specifies the expected property that is relevant to the type...
.maxLength(64)
.hasUppercase()
.hasNumber();Every validation returns a valid, an errors and a passed field:
const result: {
valid: boolean; // indicates whether the validation was successful
errors: { [key: string]: any[] } | undefined; // contains error messages
passed: T | Partial<T> | undefined; // holds the value(s) that passed the validation
};For primitive types
For primitive types, the error object contains only the "" field with the relevant error messages in an array.
If there is an error (even in array or object validations), the "" field always contains one or more error messages. The reason for using "" instead of accessing error messages directly is to standardize the structure of the error object. As a result, it doesn't matter if the validated element is a number or an object, if the validation fails, the "" field will hold some relevant messages. This means that the same logic can be used to access the error message for primitive and complex types as well.
The result object has also an extra passed field containing value that have matched the criteria. For primitive types, it is most useful when you allow the validator to cast the value if it is of the wrong type.
Let's see a few examples:
const result: {
valid: boolean;
errors: {
"": any[];
};
passed: T | undefined; // string | number | undefined
};import validator from "typic";
const schema = validator()
.number("Not a number") /* Error messages are optional */
.min(0, "Should be at least 0")
.max(10, "Should be at most 10")
.prime("Should be a prime");
let result;
result = schema.validate("");
/*
{
valid: false,
errors: {
"": ["Not a number!"]
},
passed: undefined
}
*/
result = schema.validate(-1);
/*
{
valid: false,
errors: {
"": ["Should be at least 0", "Should be a prime"]
},
passed: undefined
}
*/
result = schema.validate(0);
/*
{
valid: false,
errors: {
"": ["Should be a prime"]
},
passed: undefined
}
*/
result = schema.validate(2);
/*
{
valid: true,
errors: undefined,
passed: 2
}
*/Primitive types with schemas are:
For complex types
Array
For Array types, the error object contains a "" field with error messages relevant for the entire array, and also "<index>" fields with error messages relevant for the given element. The relevant error messages are the result of other validations and as such they have the same structures as we have seen before.
The result object contains also the passed field containing the elements that have matched the criteria.
const result: {
valid: boolean;
errors: {
"": any[];
[key: string]: {};
};
passed: [];
};import validator from "typic";
const schema = validator()
.array()
.minLength(2)
.each(
validator()
.number()
.min(0)
.max(10)
);
let result;
result = schema.validate({});
/*
{
valid: false,
errors: {
"": [
"Value is not an array!"
]
},
passed: undefined // <- the validated element is not an array, so we got nothing
}
*/
result = schema.validate([]);
/*
{
valid: false,
errors: {
"": [
"Array should have at least 2 elements!"
]
},
passed: [] // <- the validated element really is an array, so at least we got that
}
*/
result = schema.validate([0, -2, 1]);
/*
{
valid: false,
errors: {
"": [
"Array elements should satisfy the 'each' condition!"
],
"1": {
"": [
"Value should be 0 at least!"
]
}
},
passed: [ // <- the values 0 and 1 passed the validation, so we see them in this field
0,
null,
1
]
}
*/
result = schema.validate([0, 2, 1]);
/*
{
valid: true,
errors: {},
passed: [
0,
2,
1
]
}
*/Object
Object type validator is called JSON, because it accepts Javascript Objects and JSON strings as well. Because arrays are objects, a json() validator can be used against them as well.
Just as with arrays, the error object contains a "" field with error messages relevant for the entire object, and also "<fieldname>" fields with error messages relevant for the respective field. The result object also contains an extra passed field containing the elements that have matched the criteria.
const schema = validator()
.json()
.keys({
email: validator()
.string()
.regex(/\@/), // I know, I know...
password: validator()
.string()
.minLength(8)
.hasUppercase(),
});
let result;
result = schema.validate(0);
/*
{
valid: false,
errors: {
"": [
"Value is not a JSON!"
]
},
passed: undefined
}
*/
result = schema.validate([]);
/*
{
valid: false,
errors: {
"email": {
"": [
"Value is not a string!"
]
},
"password": {
"": [
"Value is not a string!"
]
},
"": [
"JSON doesn't match key schema!"
]
},
passed: {}
}
*/
result = schema.validate({});
/*
{
valid: false,
errors: {
"email": {
"": [
"Value is not a string!"
]
},
"password": {
"": [
"Value is not a string!"
]
},
"": [
"JSON doesn't match key schema!"
]
},
passed: {}
}
*/
result = schema.validate({
email: "[email protected]",
password: "abcd",
});
/*
{
valid: false,
errors: {
password: {
"": [
"Value should be at least 8 characters long!",
"Value should contain an uppercase character!'"
]
},
"": [
"JSON doesn't match key schema!"
]
},
passed: {
email: "[email protected]"
}
}
*/
result = schema.validate({
email: "[email protected]",
password: "Password1",
});
/*
{
valid: true,
errors: undefined,
passed: {
email: "[email protected]",
password: "Password1"
}
}
*/For 'any' type
Calling the validator factory validator() return an AnySchema. There the following methods are available:
number()-> returns a NumberSchemastring()-> returns a StringSchemaboolean()-> returns a BooleanSchemaarray()-> returns an ArraySchemajson()-> returns a JSONSchema
Apart from the typed schemas, three logical functions are available too on an AnySchema:
and(options)-> instructs the AnySchema to validate only if every option validatesor(options)-> instructs the AnySchema to validate only if some option validatesnot(option)-> instructs the AnySchema to validate only if the option does not validate
After calling and, or or not these functions become unavailable, i.e. one AnySchema can validate only in one of these modes.
// Validates only if the value is either a string or a number
const schema = validator().or([validator().string(), validator().number()]);
// Validates only if the array has only string values and its length is divisible by 3
const schema = validator().and([
validator()
.array()
.each([validator().string()]),
validator()
.json()
.keys({
length: validator()
.number()
.multipleOf(3),
}),
]);
const schema = validator()
.or([validator().string(), validator().number()])
.and(/*...*/); // `and` is not available when using types
// also force-calling and() is ineffectiveAnd that is the gist of it.
