When I created the library for data validation quartet
, I took the following landmarks:
In this article I will show how the library quartet
understands what the words βShortβ and βSimpleβ mean in the context of the approach to validation.
How does it work quartet
?
When is it needed? It is needed when data validation is needed.
What is validation? Check data for compliance. Most often types.
How does quartet
this help? It creates a validation function based on a declarative description of requirements - a scheme. The compiler function v
converts the circuit into a validation function. Also v
, prepared schemes and methods are stored inside to create more complex schemes. See the documentation for more details .
How it works?
- You write a scheme
- You give it to the input of the compiler function
v
to get the validation function. - The validation function is ready to use!
Let's quartet validate all the data without straining the brain in seven approaches.
.
:
type Answer = 42;
quartet
:
const answerSchema = 42;
- :
import { v } from "quartet";
const checkAnswer = v(42);
. β .
, . β .
. , , .
const checkNumber = (x) => typeof x === "number";
const checkString = (x) => typeof x === "string";
const checkBoolean = (x) => typeof x === "boolean";
const checkSymbol = (x) => typeof x === "symbol";
:
const checkSomeType = x => typeof x === "<type>", <type> β
, :
, :
const checkNumber = v(v.number);
const checkNumber = (x) => typeof x === "number";
quartet
:
const checkFunction = v(v.function);
const checkFunction = (x) => typeof x === "function";
. C β v.
.
«»
:
type NullableString = string | null;
quartet
:
const nullableStringSchema = [v.string, null];
:
const checkNullableString = v([v.string, null]);
:
type VariantSchema = Schema[];
. β .
«»
type Password = string
. v.minLength()
v.test(RegExp)
const stringSchema = v.string;
const min8Schema = v.minLength(8);
const atLeastOneDigitSchema = v.test(/\d/);
const atLeastOneLetterSchema = v.test(/[A-Za-z]/);
v.and()
:
const passwordSchema = v.and(
stringSchema,
min8Schema,
atLeastOneDigitSchema,
atLeastOneLetterSchema,
)
. v.and(, , ...)
.
Person
:
interface Person {
name: string
age: number
}
, Person
?
, name
age
. string
number
. !
, , .
β !
:
const personSchema = {
name: v.string,
age: v.number,
};
:
interface ObjectInterfaceSchema {
[propertyName: string]: Schema;
}
. β , β , β .
:
type Numbers = number[];
v.arrayOf()
. .
const checkNumbers = v(v.arrayOf(v.number));
. v.arrayOf( )
.
quartet
.
. Ρ v.custom( )
:
const evenSchema = v.custom((x) => x % 2 === 0)
const evenNumberSchema = v.and(
v.number,
evenSchema,
);
. v.custom( )
.
- β .
- C β
v.
. - β .
v.and(, , ...)
.- β , β , β .
v.arrayOf( )
.v.custom( )
.
P.S.
. quartet
:
. 4 , .
, !