JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 45
  • Score
    100M100P100Q53041F
  • License ISC

A lightweight and flexible schema validation library. Allows defining object schemas with properties validation rules, supports built-in JavaScript data types, custom validation functions, default values, and nested schemas.

Package Exports

  • als-schema
  • als-schema/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (als-schema) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

als-schema

The Schema class provides a mechanism to validate and manipulate JavaScript objects based on predefined rules or 'schemas'. The Schema class is designed to be extensible, with custom validators and asynchronous validation. This allows complex validation scenarios, such as making a network request as part of validation.

Installation and import

npm install als-schema

Use as common js:

const Schema = require('als-schema');

Use as module:

import Schema from 'als-schema/schema.mjs'

Use in browser as module:

import Schema from '/node_modules/als-schema/schema.mjs'

Use as script in browser:

<script src="/node_modules/als-schema/schema.js"></script>

Creating schema

Syntax:

const schema = {
   key:validator,
   key1:[...validators]
}
const someSchema = new Schema(schema:object,name:string)
const obj = {key:'value',key1:'value',...}
const errors = someSchema(obj):array

Each validator can be:

  • undefined or null
  • Type validators - checking value type only if value not undefined or null and adding error to errors. Don't return false. Supported types:
    • String
    • Boolean
    • BigInt
    • Number
    • Object
    • Array
  • Custom validators as function which get parameters (value,{key,obj,errors,error,params,prev})
  • Any value as default value for undefined/null
  • Nested schema

Skiping and terminating validation

If validator return false - validation process terminated. If validator return number (n) bigger than zero, next n validators will be skipped.

Example

const getAge = (val,{obj}) => {obj.age = new Date().getFullYear() - obj.bd;}
const getVote = (val,{obj}) => {obj.canVote = obj.age >= 18;}
const userSchema = new Schema({
   name: ['no name',String], // If undefined value is 'no name'. If defined, check if value String and add error if not
   bd:(value,{obj}) => { // custom validation
      if(isNaN(value)) {delete obj.bd; return false}
   },
   age: getAge, // custom validation
   canVote: getVote, // custom validation
},'user');

Validate an object:

const user = {bd:1980}
const errors = userSchema.validate(user);
console.log({user,errors}); // Logs any validation errors

Result:

{
  user: { bd: 1980, name: 'no name', age: 43, canVote: true },
  errors: []
}

Let's try another one:

const user = {bd:'year1980',name:'Alex'}
const errors = userSchema.validate(user);
console.log({user,errors}); // Logs any validation errors

result:

{
  user: { name: 'Alex' },
  errors: [
    {
      schema: 'user',
      validator: 'bd',
      key: 'bd',
      message: 'Birthday is not valid',
      stack: undefined
    }
  ]
}

On example above, you can see the structure of error which builded by error function which is one of validator parameters as part of options parameter. In addition, this structure is used also then validator drops error. In this case, the stack property will include error's stack.

Synchronous and Asynchronous Validation

On constructor, each schema object checked for async functions. If at least one validator is a async function, validate method will return promise.

Key Validation Order

The keys of an object are validated in the order they were added to the schema. If an asynchronous validator is encountered during validation, the schema.validate() method will await its completion before moving to the next key.

However, keep in mind that in older JavaScript environments (such as some versions of Internet Explorer), the order of object keys is not guaranteed, and the validation order might not match the order in which keys were added to the schema.

In case of nested schemas, if the nested schema has asynchronous validators, the parent schema will wait for the nested schema's validation to complete before moving to the next key.

This ordered validation process allows for complex scenarios where the validation of some fields depends on the validation of previous fields.