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

express-validate-system

v2.0.0

Published

A lightweight express middleware to easily validate user input in requests.

Downloads

6

Readme

Validate

Build Status Coverage Status

A lightweight express middleware to easily validate user input in requests.

import validateMiddleware from 'express-validate-system';

const validationRules = {
	body: {
		email: (email) => ({
			'Please provide an email.': email,
			'Invalid email.': email && email.indexOf('@') !== -1,
		}),
		password: (password) => ({
			'No password provided.': password,
			'Your password is not long enough.': password && password.length > 6,
		}),
	},
};

app.post('/api/users', validateMiddleware(validationRules), (request, response) => {
	// TODO: Create the user here. request.body.email and request.body.password are validated based on the rules in validationRules because of the validateMiddleware.
});

app.use((error, request, response, next) => {
	// The error middleware should handle the response. `error` is a Boom#badRequest error with an array of errorMessages in it's data property.
});

Validation Rules

To validate requests, you need to pass validation rules to the validate middleware. The rules per property are a validator function. A validator function returns an object with one or more error messages as keys and the validation as value where true is valid and false invalid.

For example, the following creates a rule on body.email which validates if the email exists and if it's valid (valid as in an @ exists, this is for demonstration purposes only):

const validationRules = {
	// The scope of the validation rule is request.body. You could just as well validate request.query, if you want.
	body: {
		// We want to validate the email property on the body. We
		// create a validator function which returns an object with
		// multiple error messages and the validation result as
		// value (where true is valid and false is invalid).
		email: (email) => ({
			// Check if the email exists.
			'Please provide your email.': email,
			// Check if the email contains an @ character.
			'Please provide a valid email.': email && email.indexOf('@') !== -1,
		}),
	},
};

Now, if a request with the body { email: null } is parsed, the validate will call the validator function and parse the object. 'Please provide your email.': email, will be false and thus email is considered invalid. validate will continue parsing all validation rules. 'Please provide a valid email.': email && email.indexOf('@') !== -1, will also be false and thus again invalid.

Nested Rules

You can also nest validation rules. This makes it easier to validate nested properties. The below snippet creates a validate rule for request.body.address.streetName and request.body.address.postalCode:

const validationRules = {
	body: {
		address: {
			streetName: (streetName) => ({
				'Please fill in your street.': streetName,
			}),
			postalCode: (postalCode) => ({
				'Please fill in your postal code.': postalCode,
			}),
		},
	},
};

Arrays

You can also validate all items in an array.

const validationRules = {
	body: {
		list: [{
			name: (name) => ({
				'Name should be set': name,
			}),
		}],
		'list.length': (length) => ({
			'There should be 3 items in the list.': length === 3,
		}),
	}
}

The will also check the length of the list in request's body. You can use the dot notation to check specific properties.

References

You can also reference other properties. The validator function's arguments contain all parent objects up to the root object (the request).

const validationRules = {
	body: {
		value: (value) => ({
			'Value must be bigger than 42.': value > 42,
		}),
		otherValue: (otherValue, body, request) => ({
			'The other value should be smaller than value.': otherValue < body.value,
		}),
	},
};

Custom errors

Since version 2.0 this library passes Boom errors to the next callback. To create your own errors, pass a callback to the validateMiddleware which creates error messages.

const middleware = validateMiddleware({
	body: {
		test: (test) => ({
			'Test should be set to 123.': test === 123,
		}),
	},
}, (errorMessages) => new Error('This is my custom error.'));

Validate

You can also use the validate function directly without using the middleware. Pass the validation rules to validate and it returns an array with one or more error messages.

import { validate } from 'express-validate-system';

const errorMessages = validate(validationRules);