obj-schema-validation

Object validation

Usage no npm install needed!

<script type="module">
  import objSchemaValidation from 'https://cdn.skypack.dev/obj-schema-validation';
</script>

README

obj-schema-validation

Validate JavaScript objects.

Usage

import { Schema, Validators } from 'obj-schema-validation';

let user = new Schema({
  name: String,
  age: {
    type: Validators.integer,
    optional: true
  },
  role: { enum: ['admin', 'user', 'client'] }
});

let request = new Schema({
  users: [user]
});

let errors = request.validate({
  users: [{
    name: 'John',
    age: '34',
    role: 'Admin'
  }]
});

=> ["'users[0].age' must be of type Number",
    "'users[0].role' must be equal to 'admin'"]

Built-in validators

  • each – Array
    [<node>]
    { type: Array, each: <node> }
    
  • elements – Tuple
    [<a>, <b>, ...] (0, 2, or more)
    { type: Array, elements: [<a>, <b>, ...] }
    
  • enum – One of
    { enum: [<a>, <b>] } (1 or more)
    
  • multiple – Combined validators
    { multiple: [<validator>, <validator>, ...] }
    
  • optional – Optional value
    { optional: true }
    
  • pairs – Key-value pairs (specifies type of values, keys are always strings)
    { type: Object, pairs: Number }
    
  • pattern – Regular expressions
    /.../
    { type: String, pattern: /.../ }
    
  • properties – Object
    { a: <a>, b: <b>, ... }
    { type: Object, properties: { a: <a>, b: <b> } }
    
  • type – Constructor
    <Class>
    { type: <Class> }
    
  • validate – Custom validator
    { validate: (value, options) => {
      // -> array of errors, boolean or undefined (undefined is the same as [])
    } }
    
  • value – Exact value
    <non-object value>
    { value: <non-object value> }
    

Additional validators

  • integer – Must be a finite integer (not NaN)
  • bounded(min, max) – Must be a finite number (not NaN) between min and max
  • number - Must be a finite number (not NaN)