Sontaran
Sontaran is a javascript validator library. It has a lot validation options out of the box and all validators are extendable with custom validation functions.
Some key features
- Completely written in Typescript
- CommonJS build for Node JS
- Tree shakable ES build
- Fluid, chainable api
- Support for async validators with the
validateAsync
method
Installation
Sontaran can be installed using npm.
npm install --save sontaran
For the complete code including all tests the repo can be cloned.
git clone https://github.com/Barry127/sontaran.gitcd sontarannpm run test
Getting Started
The object().schema()
function takes a schema of Sontaran validators as an argument.
In this example:
username
- Must be a string
- Cannot be only empty characters (spaces, tabs, return, ...)
- Must have a length between 3 and 10 characters
- Must match the given RegExp (only contain alphanumeric characters and dash, underscore)
- Must be a valid email
password
- Must be a string
- Must have a length of at least 8 characters
; const schema = ; // Valid schema (return true)schema; /** => { valid: true, value: { username: 'sontaran', email: 'email@domain.com', password: 'mySuperSecretPassword }}*/ // invalid usernameslet a = 123; // => not a stringlet b = ' \t\r'; // => Empty characterslet c = 'aa'; // => too shortlet d = 'Hello-World'; // => too longlet e = 'B@dInput'; // => invalid character
Sontarans custom
can take any ValidatorFunction
function as argument to validate and / or transform a value.
; // value cannot be root and is transformed to lowercaseconst myCustomValidator = { if value === 'root' throw 'root is not allowed'; return value;}; const schema = ; // valid result transformed to lowercaseconst result = schemalabel'username';/* => { valid: true, value: 'admin'}*/ // invalid resultconst result = schemalabel'username';/* => { valid: false, value: 'Root', errors: [{ field: 'username', message: 'root is not allowed', type: 'root is not allowed' }]}*/