@theshelf/validation
v0.0.3
Published
The validation package provides a universal interaction layer with an actual data validation solution.
Keywords
Readme
Validation | The Shelf
The validation package provides a universal interaction layer with an actual data validation solution.
Installation
npm install @theshelf/validationImplementations
Currently, there is only one implementation:
- Zod - implementation for the currently popular Zod library.
Configuration
The used implementation needs to be configured in the .env file.
VALIDATION_IMPLEMENTATION="zod"How to use
An instance of the configured validator implementation can be imported for performing validation operations.
import validator from '@theshelf/validation';
// Perform operations with the validator instanceOperations
import validator, { ValidationSchema, ValidationResult } from '@theshelf/validation';
const data = {
name: 'John Doe',
age: '42'
};
const schema: ValidationSchema = {
name: { message: 'Invalid name', STRING: { required: true, minLength: 4, maxLength: 40 } },
nickname: { message: 'Invalid nickname', STRING: { required: false, , pattern: '^[a-z]+$' } },
age: { message: 'Invalid age', NUMBER: { required: true, minValue: 18, maxValue: 99 } }
};
// Validate data
const result: ValidationResult = validator.validate(data, schema);Validation scheme options
A basic validation scheme has the following structure.
const schema: ValidationSchema = {
fieldName1: { TYPE: { /* type options */ } },
fieldName2: { TYPE: { /* type options */ } },
...
}Note that a custom validation error message can optionally be set per field.
The following types are supported:
- STRING
required: booleanminLength?: numbermaxLength?: numberpattern?: string
- NUMBER
required: booleanminValue?: numbermaxValue?: number
- ARRAY
required: booleanminLength?: numbermaxLength?: numbervalidations?: Partial<Validation>
- BOOLEAN
required: boolean
- DATE
required: boolean
- UUID
required: boolean
- EMAIL
required: boolean
- URL
required: boolean
Validation result structure
The validation result has two fields:
- invalid - boolean indicating if at least one of the fields is invalid.
- messages - map containing the validation error messages per field.
