@arnaugra/scribe-validator
v1.0.1
Published
A small library for validating forms.
Downloads
11
Maintainers
Readme
Scribe Validator
Lightweight and simple validator for requests (similar to Laravel-Validation).
Install
npm i scribe-validatorAnd import
import Scribe from 'scribe-validator';Usage
Consists in two objects, one with the data to validate, ando another with the rules for each role.
const validation = new Scribe(
{ field: "value" },
{ "field": ["required", "string"] }
);While using TypeScript, you can use the types.
import type {
Data, // data to validate
Rules, // rules
} from 'scribe-validator'Once the data is validated, you can use tree attributes
// return a boolean depending if the validation is successful
validation.passes
// returns true / false
// returns the errors
validation.errors
// returns {
// field: [
// 'error 1',
// 'error 2',
// ...
// ]
// }
// returns the data vanidated
validation.validated
// returns {
// field: 'value'
// }
// if the field is nested, each field is asigned to the array index
// returns {
// projects: {
// '0': {
// title: 'project 1',
// },
// '1': {
// title: 'project 2',
// },
// ...
// }
// }Validations
Rules must be an array with the different validators needed
Example
import { Scribe } from scribe-validator;
const request = {
username: "John",
userSince: "2023-03-14",
groups: [
{
name: "dogs",
notify: true
},
{
name: "cats",
notify: false
}
]
}
const rules = {
"username": ["required", "string", "min:3", "max:16"],
"userSince": ["required", "isDate"],
"groups": ["array"],
"groups.*.name": ["requiredIf:groups", "string"],
"groups.*.notify": ["requiredIf:groups", "boolean"]
}
const validation = new Scribe(request, rules);
if (!validation.passes) {
const errors = validation.errors;
// ... handle errors
}
const validatedData = validation.validated;
// ... use validatedData