validate
Validate object properties in javascript.
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
- Schema
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
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
Examples
prop.length({ min: 8, max: 255 })
prop.length(10)
Returns Property
size
Registers a validator that checks size.
Parameters
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
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
path String full path using dot-notation
rules (Object | Array | String | Schema | Property)? rules to apply
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
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
- Schema
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
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
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
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
- __INLINE_CODE_75__ String full path using dot-notation
- __INLINE_CODE_76__ (Object | Array | String | Schema | Property)? rules to apply
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