npm.io
5.2.0 • Published 4 years ago

validate

Licence
MIT
Version
5.2.0
Deps
3
Size
70 kB
Vulns
0
Weekly
0
Stars
235

validate

Validate object properties in javascript.

npm version Build Status Codecov

Usage

Define a schema and call .validate() with the object you want to validate. The .validate() function returns an array of validation errors.

import Schema from 'validate'

const user = new Schema({
  username: {
    type: String,
    required: true,
    length: { min: 3, max: 32 }
  },
  pets: [{
    name: {
      type: String
      required: true
    },
    animal: {
      type: String
      enum: ['cat', 'dog', 'cow']
    }
  }],
  address: {
    street: {
      type: String,
      required: true
    },
    city: {
      type: String,
      required: true
    }
    zip: {
      type: String,
      match: /^[0-9]+$/,
      required: true
    }
  }
})

const errors = user.validate(obj)

Each error has a .path, describing the full path of the property that failed validation, and a .message describing the error.

errors[0].path //=> 'address.street'
errors[0].message //=> 'address.street is required.'

Custom error messages

You can override the default error messages by passing an object to Schema#message().

const post = new Schema({
  title: { required: true }
})

post.message({
  required: (path) => `${path} can not be empty.`
})

const [error] = post.validate({})
assert(error.message = 'title can not be empty.')

It is also possible to define messages for individual properties:

const post = new Schema({
  title: {
    required: true,
    message: 'Title is required.'
  }
})

And for individual validators:

const post = new Schema({
  title: {
    type: String,
    required: true,
    message: {
      type: 'Title must be a string.',
      required: 'Title is required.'
    }
  }
})
Nesting

Objects and arrays can be nested as deep as you want:

const event = new Schema({
  title: {
    type: String,
    required: true
  },
  participants: [{
    name: String,
    email: {
      type: String,
      required: true
    },
    things: [{
      name: String,
      amount: Number
    }]
  }]
})

Arrays can be defined implicitly, like in the above example, or explicitly:

const post = new Schema({
  keywords: {
    type: Array,
    each: { type: String }
  }
})

Array elements can also be defined individually:

const user = new Schema({
  something: {
    type: Array,
    elements: [
      { type: Number },
      { type: String }
    ]
  }
})

Nesting also works with schemas:

const user = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  }
})

const post = new Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  author: user
})

If you think it should work, it probably works.

Naming conflicts

Validate will naively assume that a nested object where all property names are validators is not a nested object.

const schema = new Schema({
  pet: {
    type: {
      required: true,
      type: String,
      enum: ['cat', 'dog']
    }
  }
});

In this example, the pet.type property will be interpreted as a type rule, and the validations will not work as intended. To work around this we could use the slightly more verbose properties rule:

const schema = new Schema({
  pet: {
    properties: {
      type: {
        required: true,
        type: String,
        enum: ['cat', 'dog']
      }
    }
  }
});

In this case the type property of pets.properties will be interpreted as a nested property, and the validations will work as intended.

Custom validators

Custom validators can be defined by passing an object with named validators to .use:

const hexColor = val => /^#[0-9a-fA-F]$/.test(val)

const car = new Schema({
  color: {
    type: String,
    use: { hexColor }
  }
})

Define a custom error message for the validator:

car.message({
  hexColor: path => `${path} must be a valid color.`
})
Custom types

Pass a constructor to .type to validate against a custom type:

class Car {}

const user = new Schema({
  car: { type: Car }
})
Chainable API

If you want to avoid constructing large objects, you can add paths to a schema by using the chainable API:

const user = new Schema()

user
  .path('username').type(String).required()
  .path('address.zip').type(String).required()

Array elements can be defined by using $ as a placeholder for indices:

const user = new Schema()
user.path('pets.

This is equivalent to writing

const user = new Schema({ pets: [{ type: String }]})
Typecasting

Values can be automatically typecast before validation. To enable typecasting, pass an options object to the Schema constructor with typecast set to true.

const user = new Schema(definition, { typecast: true })

You can override this setting by passing an option to .validate().

user.validate(obj, { typecast: false })

To typecast custom types, you can register a typecaster:

class Car {}

const user = new Schema({
  car: { type: Car }
})

user.typecaster({
  Car: (val) => new Car(val)
})
Property stripping

By default, all values not defined in the schema will be stripped from the object. Set .strip = false on the options object to disable this behavior. This will likely be changed in a future version.

Strict mode

When strict mode is enabled, properties that are not defined in the schema will trigger a validation error. Set .strict = true on the options object to enable strict mode.

API

Table of Contents
Property

A property instance gets returned whenever you call schema.path(). Properties are also created internally when an object is passed to the Schema constructor.

Parameters
  • name String the name of the property
  • schema Schema parent schema
message

Registers messages.

Parameters
Examples
prop.message('something is wrong')
prop.message({ required: 'thing is required.' })

Returns Property

schema

Mount given schema on current path.

Parameters
  • schema Schema the schema to mount
Examples
const user = new Schema({ email: String })
prop.schema(user)

Returns Property

use

Validate using named functions from the given object. Error messages can be defined by providing an object with named error messages/generators to schema.message()

The message generator receives the value being validated, the object it belongs to and any additional arguments.

Parameters
  • fns Object object with named validation functions to call
Examples
const schema = new Schema()
const prop = schema.path('some.path')

schema.message({
  binary: (path, ctx) => `${path} must be binary.`,
  bits: (path, ctx, bits) => `${path} must be ${bits}-bit`
})

prop.use({
  binary: (val, ctx) => /^[01]+$/i.test(val),
  bits: [(val, ctx, bits) => val.length == bits, 32]
})

Returns Property

required

Registers a validator that checks for presence.

Parameters
  • bool Boolean? true if required, false otherwise (optional, default true)
Examples
prop.required()

Returns Property

type

Registers a validator that checks if a value is of a given type

Parameters
Examples
prop.type(String)
prop.type('string')

Returns Property

string

Convenience method for setting type to String

Examples
prop.string()

Returns Property

number

Convenience method for setting type to Number

Examples
prop.number()

Returns Property

array

Convenience method for setting type to Array

Examples
prop.array()

Returns Property

date

Convenience method for setting type to Date

Examples
prop.date()

Returns Property

length

Registers a validator that checks length.

Parameters
  • rules (Object | Number) object with .min and .max properties or a number
    • rules.min Number minimum length
    • rules.max Number maximum length
Examples
prop.length({ min: 8, max: 255 })
prop.length(10)

Returns Property

size

Registers a validator that checks size.

Parameters
  • rules (Object | Number) object with .min and .max properties or a number
    • rules.min Number minimum size
    • rules.max Number maximum size
Examples
prop.size({ min: 8, max: 255 })
prop.size(10)

Returns Property

enum

Registers a validator for enums.

Parameters
  • enums
  • rules Array allowed values
Examples
prop.enum(['cat', 'dog'])

Returns Property

match

Registers a validator that checks if a value matches given regexp.

Parameters
  • regexp RegExp regular expression to match
Examples
prop.match(/some\sregular\sexpression/)

Returns Property

each

Registers a validator that checks each value in an array against given rules.

Parameters
Examples
prop.each({ type: String })
prop.each([{ type: Number }])
prop.each({ things: [{ type: String }]})
prop.each(schema)

Returns Property

elements

Registers paths for array elements on the parent schema, with given array of rules.

Parameters
  • arr Array array of rules to use
Examples
prop.elements([{ type: String }, { type: Number }])

Returns Property

properties

Registers all properties from the given object as nested properties

Parameters
  • props Object properties with rules
Examples
prop.properties({
  name: String,
  email: String
})

Returns Property

path

Proxy method for schema path. Makes chaining properties together easier.

Parameters
  • args ...any
Examples
schema
  .path('name').type(String).required()
  .path('email').type(String).required()
typecast

Typecast given value

Parameters
  • value Mixed value to typecast
Examples
prop.type(String)
prop.typecast(123) // => '123'

Returns Mixed

validate

Validate given value

Parameters
  • value Mixed value to validate
  • ctx Object the object containing the value
  • path String? path of the value being validated (optional, default this.name)
Examples
prop.type(Number)
assert(prop.validate(2) == null)
assert(prop.validate('hello world') instanceof Error)

Returns ValidationError

Schema

A Schema defines the structure that objects should be validated against.

Parameters
  • obj Object? schema definition (optional, default {})
  • opts Object? options (optional, default {})
    • opts.typecast Boolean typecast values before validation (optional, default false)
    • opts.strip Boolean strip properties not defined in the schema (optional, default true)
    • opts.strict Boolean validation fails when object contains properties not defined in the schema (optional, default false)
Examples
const post = new Schema({
  title: {
    type: String,
    required: true,
    length: { min: 1, max: 255 }
  },
  content: {
    type: String,
    required: true
  },
  published: {
    type: Date,
    required: true
  },
  keywords: [{ type: String }]
})
const author = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  posts: [post]
})
path

Create or update path with given rules.

Parameters
Examples
const schema = new Schema()
schema.path('name.first', { type: String })
schema.path('name.last').type(String).required()

Returns Property

validate

Validate given obj.

Parameters
  • obj Object the object to validate
  • opts Object? options, see Schema (optional, default {})
Examples
const schema = new Schema({ name: { required: true }})
const errors = schema.validate({})
assert(errors.length == 1)
assert(errors[0].message == 'name is required')
assert(errors[0].path == 'name')

Returns Array

assert

Assert that given obj is valid.

Parameters
Examples
const schema = new Schema({ name: String })
schema.assert({ name: 1 }) // Throws an error
message

Override default error messages.

Parameters
  • name (String | Object) name of the validator or an object with name-message pairs
  • message (String | Function)? the message or message generator to use
Examples
const hex = (val) => /^0x[0-9a-f]+$/.test(val)
schema.path('some.path').use({ hex })
schema.message('hex', path => `${path} must be hexadecimal`)
schema.message({ hex: path => `${path} must be hexadecimal` })

Returns Schema

validator

Override default validators.

Parameters
  • name (String | Object) name of the validator or an object with name-function pairs
  • fn Function? the function to use
Examples
schema.validator('required', val => val != null)
schema.validator({ required: val => val != null })

Returns Schema

typecaster

Override default typecasters.

Parameters
  • name (String | Object) name of the validator or an object with name-function pairs
  • fn Function? the function to use
Examples
schema.typecaster('SomeClass', val => new SomeClass(val))
schema.typecaster({ SomeClass: val => new SomeClass(val) })

Returns Schema

Licence

MIT

).type(String)

This is equivalent to writing

__CODE_BLOCK_16__
Typecasting

Values can be automatically typecast before validation. To enable typecasting, pass an options object to the __INLINE_CODE_13__ constructor with __INLINE_CODE_14__ set to __INLINE_CODE_15__.

__CODE_BLOCK_17__

You can override this setting by passing an option to __INLINE_CODE_16__.

__CODE_BLOCK_18__

To typecast custom types, you can register a typecaster:

__CODE_BLOCK_19__
Property stripping

By default, all values not defined in the schema will be stripped from the object. Set __INLINE_CODE_17__ on the options object to disable this behavior. This will likely be changed in a future version.

Strict mode

When strict mode is enabled, properties that are not defined in the schema will trigger a validation error. Set __INLINE_CODE_18__ on the options object to enable strict mode.

API

Table of Contents
Property

A property instance gets returned whenever you call __INLINE_CODE_19__. Properties are also created internally when an object is passed to the Schema constructor.

Parameters
  • __INLINE_CODE_20__ String the name of the property
  • __INLINE_CODE_21__ Schema parent schema
message

Registers messages.

Parameters
Examples
__CODE_BLOCK_20__

Returns Property

schema

Mount given __INLINE_CODE_23__ on current path.

Parameters
  • __INLINE_CODE_24__ Schema the schema to mount
Examples
__CODE_BLOCK_21__

Returns Property

use

Validate using named functions from the given object. Error messages can be defined by providing an object with named error messages/generators to __INLINE_CODE_25__

The message generator receives the value being validated, the object it belongs to and any additional arguments.

Parameters
  • __INLINE_CODE_26__ Object object with named validation functions to call
Examples
__CODE_BLOCK_22__

Returns Property

required

Registers a validator that checks for presence.

Parameters
  • __INLINE_CODE_27__ Boolean? __INLINE_CODE_28__ if required, __INLINE_CODE_29__ otherwise (optional, default __INLINE_CODE_30__)
Examples
__CODE_BLOCK_23__

Returns Property

type

Registers a validator that checks if a value is of a given __INLINE_CODE_31__

Parameters
Examples
__CODE_BLOCK_24__ __CODE_BLOCK_25__

Returns Property

string

Convenience method for setting type to __INLINE_CODE_33__

Examples
__CODE_BLOCK_26__

Returns Property

number

Convenience method for setting type to __INLINE_CODE_34__

Examples
__CODE_BLOCK_27__

Returns Property

array

Convenience method for setting type to __INLINE_CODE_35__

Examples
__CODE_BLOCK_28__

Returns Property

date

Convenience method for setting type to __INLINE_CODE_36__

Examples
__CODE_BLOCK_29__

Returns Property

length

Registers a validator that checks length.

Parameters
  • __INLINE_CODE_37__ (Object | Number) object with __INLINE_CODE_38__ and __INLINE_CODE_39__ properties or a number
    • __INLINE_CODE_40__ Number minimum length
    • __INLINE_CODE_41__ Number maximum length
Examples
__CODE_BLOCK_30__

Returns Property

size

Registers a validator that checks size.

Parameters
  • __INLINE_CODE_42__ (Object | Number) object with __INLINE_CODE_43__ and __INLINE_CODE_44__ properties or a number
    • __INLINE_CODE_45__ Number minimum size
    • __INLINE_CODE_46__ Number maximum size
Examples
__CODE_BLOCK_31__

Returns Property

enum

Registers a validator for enums.

Parameters
  • __INLINE_CODE_47__
  • __INLINE_CODE_48__ Array allowed values
Examples
__CODE_BLOCK_32__

Returns Property

match

Registers a validator that checks if a value matches given __INLINE_CODE_49__.

Parameters
  • __INLINE_CODE_50__ RegExp regular expression to match
Examples
__CODE_BLOCK_33__

Returns Property

each

Registers a validator that checks each value in an array against given __INLINE_CODE_51__.

Parameters
Examples
__CODE_BLOCK_34__

Returns Property

elements

Registers paths for array elements on the parent schema, with given array of rules.

Parameters
  • __INLINE_CODE_53__ Array array of rules to use
Examples
__CODE_BLOCK_35__

Returns Property

properties

Registers all properties from the given object as nested properties

Parameters
  • __INLINE_CODE_54__ Object properties with rules
Examples
__CODE_BLOCK_36__

Returns Property

path

Proxy method for schema path. Makes chaining properties together easier.

Parameters
  • __INLINE_CODE_55__ ...any
Examples
__CODE_BLOCK_37__
typecast

Typecast given __INLINE_CODE_56__

Parameters
  • __INLINE_CODE_57__ Mixed value to typecast
Examples
__CODE_BLOCK_38__

Returns Mixed

validate

Validate given __INLINE_CODE_58__

Parameters
  • __INLINE_CODE_59__ Mixed value to validate
  • __INLINE_CODE_60__ Object the object containing the value
  • __INLINE_CODE_61__ String? path of the value being validated (optional, default __INLINE_CODE_62__)
Examples
__CODE_BLOCK_39__

Returns ValidationError

Schema

A Schema defines the structure that objects should be validated against.

Parameters
  • __INLINE_CODE_63__ Object? schema definition (optional, default __INLINE_CODE_64__)
  • __INLINE_CODE_65__ Object? options (optional, default __INLINE_CODE_66__)
    • __INLINE_CODE_67__ Boolean typecast values before validation (optional, default __INLINE_CODE_68__)
    • __INLINE_CODE_69__ Boolean strip properties not defined in the schema (optional, default __INLINE_CODE_70__)
    • __INLINE_CODE_71__ Boolean validation fails when object contains properties not defined in the schema (optional, default __INLINE_CODE_72__)
Examples
__CODE_BLOCK_40__ __CODE_BLOCK_41__
path

Create or update __INLINE_CODE_73__ with given __INLINE_CODE_74__.

Parameters
Examples
__CODE_BLOCK_42__

Returns Property

validate

Validate given __INLINE_CODE_77__.

Parameters
  • __INLINE_CODE_78__ Object the object to validate
  • __INLINE_CODE_79__ Object? options, see Schema (optional, default __INLINE_CODE_80__)
Examples
__CODE_BLOCK_43__

Returns Array

assert

Assert that given __INLINE_CODE_81__ is valid.

Parameters
Examples
__CODE_BLOCK_44__
message

Override default error messages.

Parameters
  • __INLINE_CODE_84__ (String | Object) name of the validator or an object with name-message pairs
  • __INLINE_CODE_85__ (String | Function)? the message or message generator to use
Examples
__CODE_BLOCK_45__ __CODE_BLOCK_46__

Returns Schema

validator

Override default validators.

Parameters
  • __INLINE_CODE_86__ (String | Object) name of the validator or an object with name-function pairs
  • __INLINE_CODE_87__ Function? the function to use
Examples
__CODE_BLOCK_47__ __CODE_BLOCK_48__

Returns Schema

typecaster

Override default typecasters.

Parameters
  • __INLINE_CODE_88__ (String | Object) name of the validator or an object with name-function pairs
  • __INLINE_CODE_89__ Function? the function to use
Examples
__CODE_BLOCK_49__ __CODE_BLOCK_50__

Returns Schema

Licence

MIT

Keywords