@gnx-utilities/validators
v0.0.83
Published
Fluent Validations is a library that allows you to create validations for your entities and properties in a simple way.
Downloads
11
Maintainers
Readme
📝 Fluent Validations
Fluent Validations is a library that allows you to create validations for your entities and properties in a simple way.
📦 Installation
npm install @gnx-utilities/validators
pnpm add @gnx-utilities/validators
yarn add @gnx-utilities/validators
bun add @gnx-utilities/validators
📖 Usage
import { FluentValidation } from '@gnx-utilities/validators'
const email = '[email protected]'
const validation = FluentValidation
.create()
.for({value: email })
.isRequired()
.isEmail()
console.log(validation.validate()) // true
console.log(validation.softValidation()) // { isValid: true, errors: [], totalErrors: 0 }
console.log(validation.getErrors()) // []
const wrongValidation = FluentValidation
.create()
.for({value: 'John Doe' })
.isEmail()
console.log(wrongValidation.validate()) // false
console.log(wrongValidation.softValidation()) // { isValid: false, errors: [ 'The value is not a valid email' ], totalErrors: 1 }
console.log(wrongValidation.getErrors()) // [ 'The value is not a valid email' ]
import { ModelValidator } from '@gnx-utilities/validators'
const user = {
name: 'John',
email: '[email protected]',
age: 20
}
const validation = ModelValidator
.create()
.for({model: user })
.withProperty(({ name }) => name === 'John')
.withProperty(({ email }) => email === '[email protected]')
.withProperty(({ age }) => age === 20)
console.log(validation.validate()) // true
console.log(validation.softValidation()) // { isValid: true, errors: [], totalErrors: 0 }
console.log(validation.getErrors()) // []
const wrongValidation = ModelValidator
.create()
.for({model: user })
.withProperty(({ name }) => name === 'Jane')
.withProperty(({ email }) => email === '[email protected]')
.withProperty(({ age }) => age === 50)
console.log(wrongValidation.validate()) // false
console.log(wrongValidation.softValidation()) // { isValid: false, errors: [ 'The property name is not valid', 'The property email is not valid', 'The property age is not valid' ], totalErrors: 3 }
console.log(wrongValidation.getErrors()) // [ 'The property name is not valid', 'The property email is not valid', 'The property age is not valid' ]