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

validate-this

v1.5.2

Published

Easily validate deep form structures using both premade and custom validation rules.

Downloads

438

Readme

Build Status codecov

validate-this

validate-this is a validation library that applies validation rules to structured form data. It also allows you to define your own validation rules.

Validating Form Data

Imagining that we have structured form data that looks like:

const formData = {
  username: '',
  email: 'bob'
}

Then we could pass that object into the function below:

import { validator } from 'validate-this'

function validate(values) {
  return validator(values, v => {
    v.validate('username', 'email').required() // the required() validation is built into the package
    v.validate('email').isValidEmail()         // the email() validation is defined below as a custom validation, read on!
  })
}

Calling the function with the formData we defined previously will return an errors object like this:

{
  username: ['required'],
  email: ['email_invalid']
}

Defining a Custom Validation

There are two ways to do your own validations: by using the satisfies validation, or by using defineValidator.

.satisfies(...rules)

Call this with your own validation rule(s). Example:

import email from 'email-validator'

function isValidEmail(value) {
  if (value && !email.validate(value)) {
    return 'email_invalid'
  }
}

function validate(values) {
  return validator(values, v => {
    v.validate('email').satisfies(isValidEmail)
  })
}

Or with multiple rules:

function greaterThan(n) {
  return value => {
    if (value <= n) {
      return 'too_small'
    }
  }
}

function lessThan(n) {
  return value => {
    if (value >= n) {
      return 'too_big'
    }
  }
}

function validate(values) {
  return validator(values, v => {
    v.validate('age').satisfies(greaterThan(17), lessThan(26))
  })
}

defineValidator(config)

In the most simple case, a rule accepts a value and returns a string if and only if the value is invalid.

import email from 'email-validator'
import { defineValidator } from 'validate-this'

defineValidator({
  name: 'isValidEmail',
  rule: value => {
    if (value && !email.validate(value)) {
      return 'email_invalid'
    }
  }
})

For more complex cases, a higher order rule can be defined. The example below is built into validate-this but makes a good demonstration.

defineValidator({
  name: 'matches',
  rule: fieldName => (val, values) => {
    if (val !== values[fieldName]) {
      return 'mismatch'
    } 
  }
})

This will validate that one field matches another. Here's a validation function that uses this validator:

function validate(values) {
  return validator(values, v => {
    v.validate('username', 'email', 'password', 'confirm').required()
    v.validate('email').isValidEmail()
    v.validate('confirm').matches('password')
  })
}

Deep Validation

If your form data is like this instead:

const formData = {
  name: 'Bob',
  address: {
    street: '123 Fake St'
  }
}

Then you can validate the address property like this:

import { validator } from 'validate-this'

function validate(values) {
  return validator(values, v => {
    v.validateChild('address', av => {
      av.validate('street').required()
    })
  })
}

Or if there's a nested array:

const formData = {
  contacts: [{
    name: 'bob',
    email: '[email protected]'
  }]
}

Then you can validate those like this:

import { validator } from 'validate-this'

function validate(values) {
  return validator(values, v => {
    v.validateChildren('contacts', cv => {
      cv.validate('name', 'email').required()
    })
  })
}

Message translation

A third argument can be provided to the validator function that will allow you to translate error messages using something like I18n. Example:

function validate(values) {
  return validator(values, v => {
    v.validate('username', 'password', 'confirm').required()
    v.validate('confirm').matches('password')
  }, (message, field) => I18n.t(`forms.newUser.${field}.${message}`))
}