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

async-validate-obj

v1.0.8

Published

a utility supports asynchronous validation

Downloads

43

Readme

async-validate-obj

a utility supports asynchronous validation

Motivation

Validation a form is a common task, I need a validation tool that:

  • run asynchronously
await validateObj({
    foo: someAsyncChecker,
}, obj)
  • curried validation function
let validator = validateObj({
    foo: someAsyncChecker
})
await validator(obj)
  • nested object validation
await validateObj({
    foo: { bar: barChecker }
}, { foo: { bar: 1 } })
  • array of checkers applied to one field
await validateObj({
    foo: [fooChecker1, fooChecker2]
}, obj)

Usage

esm way

import { validateObj, checkers } from 'async-validate-obj'

commonjs way

const { validateObj, checkers } = require('async-validate-obj')

Example

import { validateObj, checkers, ValidationError } from 'async-validate-obj'
import emailRegex from 'email-regex'

async submit(user) {
    try {
        await validateObj({
            name: checkers.required(),
            email: checkers.match(emailRegex(), 'should be a valid email'),
            pet: {
                kind: async function (kind) {
                    if (!await checkPetKind(kind)) {
                        throw new Error('pet is not allowed')
                    }
                }
            }
        }, user)
    } catch (e) {
        if (e instanceof ValidationError) {
            console.error(e.errors)
        }
        throw error
    }
}

API

validateObj(rules, obj)

params

  • rules - an object that matches the structure of the obj wait to be validated. The value is a checker or an array of checkers. each checker is a (asynchronous) function who gets two parameters, the first one is the value of matching field of obj, the second one is the obj. and this points to the current nested object, for example:

    validateObj({
        a: {
            b: function bChecker(b, root) {
            // b will be 1
            // root will be { a: { b: 1 } }
            // *this* will be {b: 1}
            }
        }
    }, { a: { b: 1 } })

    if an array of checkers provided, the field will be validated one by one, until an error met.

    a checker could throw an error or return a rejected promise when validation is failed

  • obj - the object to be validated, if not provided, a curried function will be returned

return

a promise, if all validations passed, it will be resolved, otherwise it will be rejected with an error of type ValidationError, it will has a field errors, which holds the details.

import { checkers, validateObj, ValidationError } from 'async-validate-obj'

validateObj({
    a: required('a can not be empty')
}, {})
  .catch(function (err) {
    if (err instanceof ValidationError) {
      console.log(err.errors) // { a: 'a can not be empty' }
    }
    throw err
  })

checkers.required(message)

check if a field is empty, if not, throw an error with the given message.

parameters

  • message - optional, if not provided, it defaults to 'should not be empty'

checkers.match(regex, message)

check if a field matches regex, if not, throw an error with the given message.

parameters

  • message - optional, if not provided, it defaults to 'does not match pattern ' + regex
  • regex - regular expression to be matched

Developement

$ git clone https://github.com/xiechao06/async-validate-obj.git
$ cd async-validate-obj
$ npm ci
$ npm run dev # watch and test
$ npm run build