Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

    validatepublic

    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 }
      },
      name: {
        type: 'string',
        required: true
      },
      pets: [{
        name: { type: 'string' },
        animal: { enum: ['cat', 'dog']}
      }],
      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.messsage({
      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: {
          type: 'string'
        },
        email: {
          type: 'string',
          required: true
        },
        things: [{
          name: { type: 'string' },
          amount: { type: '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.

    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.`
    })

    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.$').type('string')

    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 })

    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.

    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

    • type String type to check for

    Examples

    prop.type('string')

    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

    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

    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) == false)
    assert(prop.validate('hello world') instanceof Error)

    Returns (ValidationError | Boolean)

    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)

    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

    Licence

    MIT

    install

    npm i validate

    Downloadsweekly downloads

    2,323

    version

    4.3.1

    license

    MIT

    repository

    github.com

    last publish

    collaborators

    • avatar