README
Validee
An object validation library with minimal magic.
Installation
npm install validee
Usage
import { validee, ValideeError, ValideeFn } from 'validee'
// `value` is typed as `string`.
// Validation functions can be synchronous or asynchronous.
const trimInput: ValideeFn<string> = async (value) => {
// 1. Create an array of errors.
const errors: string[] = []
// 2. Perform any validation logic.
// if (value.length > 10) { errors.push('Must not be longer than 10 characters.') }
// 3. Return the new value and the errors.
return {
value: value.trim(),
errors,
}
}
// Define a schema, where the functions follow the same structure as above.
const schema = {
email: [trimInput, validateEmail],
username: [trimInput, validateUsername],
password: [validatePassword],
some: {
nested: {
property: [trimInput], // There is no maximum depth for your data.
},
},
}
// Example incoming data.
const badData = {
email: ' hello@example.com ', // `trimInput` will remove the spaces.
username: 'hello ', // `trimInput` will remove the space.
password: 'hello', // `validatePassword` will possibly throw an error here.
some: {
nested: {
property: ' hello', // `trimInput` will remove the space.
},
},
}
try {
// If validation passes, `goodData` is the final version of the data.
// In this case, `trimInput` will mutate `email` and `username`.
const goodData = await validee(schema, badData)
} catch (error) {
// Handle any errors.
if (error instanceof ValideeError) {
console.log(error.errors) // => { "password": ["Please choose a better password."] }
}
}