npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sequelize-validate-subfields

v1.2.0

Published

simple framework for validating subfields of JSON attributes of Sequelize models

Downloads

1,208

Readme

sequelize-validate-subfields

CircleCI Coverage Status semantic-release Commitizen friendly npm version

simple framework for validating subfields of JSON attributes of Sequelize models

Introduction

If you ever use JSON attributes in Sequelize models, you'll probably want to validate that the JSON matches some schema. And if values within the JSON come from a form filled out by a user, you'll probably want to be able to show validation errors from the server associated with the correct form field on the client.

But Sequelize ValidationErrors be default only identify the top-level attribute of each validation error. For example if you have the following validator:

  address: {
    type: Sequelize.JSON,
    validate: {
      isValid(address) {
        if (/^\d{5}$/.test(address.postalCode)) throw new Error('invalid postal code')
      }
    }
  }

You'll get an error including the following information:

ValidationError {
  errors: [
    ValidationErrorItem {
      message: 'invalid postal code',
      type: 'Validation error',
      path: 'address',
      __raw: Error {
        message: 'invalid postal code',
      },
      ...
    }
  ]
}

If you use this package to perform validation, you can tag each validation error with a specific field path instead:

  address: {
    type: Sequelize.JSON,
    validate: {
      isValid: validateSubfields(function * (address) {
        if (/^\d{5}$/.test(address.postalCode)) yield {path: ['postalCode'], message: 'invalid postal code'}
        if (states.has(address.state)) yield {path: ['state'], message: 'invalid state'}
        // etc.
      })
    }
  }

And you'll get an error including those paths:

ValidationError {
  errors: [
    ValidationErrorItem {
      message: 'validation failed',
      type: 'Validation error',
      path: 'address',
      __raw: Error {
        message: 'validation failed',
        validation: {
          errors: [
            {path: ['postalCode'], message: 'invalid postal code'},
            {path: ['state'], message: 'invalid state'},
          ]
        }
      }
    }
  ]
}

This package also provides a flattenValidationErrors function to combine subfield validation errors like in the example above with normal validation errors on non-JSON fields:

;[
  { path: ['address', 'postalCode'], message: 'invalid postal code' },
  { path: ['address', 'state'], message: 'invalid state' },
]

Installation

npm install --save sequelize-validate-subfields

API

validateSubfields(validator)

const { validateSubfields } = require('sequelize-validate-subfields')

Arguments

validator: (value: any) => Iterable<FieldValidation>

a generator function which receives the attribute value and may yield as many validation FieldValidation objects as you wish, each specifying a validation error in the following form:

{
  path: Array<string | number>,
  message: string,
}

path is the lodash.get-style path within the attribute (i.e. not including the attribute name itself) that message is associated with. For example if you define an address attribute and validator on a model like this:

  address: {
    type: Sequelize.JSON,
    validate: {
      isValid: validateSubfields(function * (address) {
        if (/^\d{5}$/.test(address.postalCode)) yield {path: ['postalCode'], message: 'invalid postal code'}
        if (states.has(address.state)) yield {path: ['state'], message: 'invalid state'}
        // etc.
      })
    }
  }

Notice that the yielded paths don't contain 'address' (the name of the attribute) themselves; they must be relative to the root of the attribute, instead of the root of the model instance.

Returns: (value: any) => void

A Sequelize custom validator function that delegates to your validator function and combines any FieldValidations it yielded into the appropriate thrown error.

flattenValidationErrors(error, [options])

const { flattenValidationErrors } = require('sequelize-validate-subfields')

Arguments

error: Sequelize.ValidationError

A ValidationError hich may contain zero or more ValidationErrorItems -- some may be from non-JSON field validation errors, and some may contain FieldValidations from validateSubfields.

options?: {formatItemMessage?: (item: ValidationErrorItem) => string}

formatItemMessage allows you to override the error messages output for ValidationErrorItems that don't contain FieldValidations using your own custom function.

Returns: Array<FieldValidation>

A flattened array of FieldValidations with paths relative to the root of the model instance instead of being relative to specific attributes. For instance, if you have the following model:

const User = sequelize.define('User', {
  username: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: {
        msg: 'required',
      },
    },
  },
  address: {
    type: Sequelize.JSON,
    validate: {
      isValid: validateSubfields(function* (address) {
        if (/^\d{5}$/.test(address.postalCode))
          yield { path: ['postalCode'], message: 'invalid postal code' }
        if (states.has(address.state))
          yield { path: ['state'], message: 'invalid state' }
        // etc.
      }),
    },
  },
})

And you validate the following fields:

{
  username: '',
  address: {
    postalCode: '123',
    state: 'KG',
  }
}

You will get a ValidationError with the following structure:

ValidationError {
  errors: [
    ValidationErrorItem {
      message: 'required',
      type: 'Validation error',
      path: 'username',
    },
    ValidationErrorItem {
      message: 'validation failed',
      type: 'Validation error',
      path: 'address',
      __raw: Error {
        message: 'validation failed',
        validation: {
          errors: [
            {path: ['postalCode'], message: 'invalid postal code'},
            {path: ['state'], message: 'invalid state'},
          ]
        }
      }
    }
  ]
}

Calling flattenValidationErrors on this will produce:

;[
  { path: ['username'], message: 'required' },
  { path: ['address', 'postalCode'], message: 'invalid postal code' },
  { path: ['address', 'state'], message: 'invalid state' },
]