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

mitra

v1.2.0

Published

Simple data/schema promise-based validator!

Downloads

5

Readme

mitra - JavaScript (node.js) validation library

npm npm

mitra is a simple library for validating data/schemata. It's promise-based and easily extendable.

Yet another JavaScript validator? Yes, JavaScript has many validation libraries. What makes them different to each other? features, design and style preferences. mitra was originally developed for another node.js package: dana which required a flexible way of adding validators, so this package was created in a Friday afternoon. That was the whole story!

Installation | Example | Documentation

Installation

$ npm i --save mitra

Example:

const mitra = require('mitra')

mitra.addAlias(
	'username', 'required|string|min_length:4|max_length:30'
);

const data = {
  user_name: 'paranoid32',
  email: '[email protected]',
  password: 'secret',
  password_confirmation: 'secret',
  job: 'In-House Philosopher',
  age: 10
}

mitra.validate(data, {
  user_name: 'user_name',
  email: 'required|email',
  password: 'required|string|min_length:8|confirmed',
  age: 'integer|min:12|max:100',
  job: {
	required: true,
	string: true,
	in: ['Professional Snuggler', 'Bride Kidnapping Expert', 'Chief Trouble Maker', 'Ex-monshiner']
  }
}).then(() => {
  // passes
}).catch(mitra.ValidationError, err => {
  // fails
})

Documentation

How it Works

The main method of mitra is the validate method. The first argument is user data and the second argument is validation constrains.

Constraints must be defined as an object (key-value pairs). Value of these keys can be either object or a string. A string value is considered a shorthand and is converted to an object. As an example the following constraint object:

{
	email: 'required|email',
	password: 'required|string|min_length:8|confirmed',
	age: 'integer|min:12|max:100',
	job: 'in:unemployed,time-waster'
}

is converted to:

{
	email: { required: true, email: true },
	password: { required: true, string: true, min_length: '8', confirmed: true },
	age: { integer: true, min: '12', max: '100' }
	job: {
		in: ['unemployed', 'time-waster']
	}
}

Note that string values are split and the actual value is passed to validators.

The constrains are passed to mitra's check method behind the scene which can also be used for validating any values. The method returns an object with 2 properties: valid and message.

mitra.check(
	value,
	rule /* name of the validator */,
	options = undefined /* options of the rule, if any */,
	attrName /* name of attribute, if any */,
	data = undefined /* all attributes, if any */,
	lang = 'en'
)

An example for the in rule:

const result = mitra.check(
	'programmer',
	'in',
	[
		'unemployed',
		'architect',
		'accountant',
		'attorney'
	],
	'job'
)
// result
// { valid: false, message: 'The selected job is invalid.' }

Aliases

An alias is a placeholder for several rules. addAlias method can be used for adding aliases!

mitra.addAlias(
	'username',
	'required|string|min_length:4|max_length:30'
);

Error objects

mitra rejects the promise created by calling validate method by an instance of ValidationError object. Each instance has these properties:

  • errors An object. Each key is an attribute name and it's value an array of error messages.

  • constraints Normalized constraints passed to the validate method.

  • data User data passed as first argument to the validate method.

Localization

mitra currently only has English locale. addLang method can used for adding other languages.

mitra.addLang('fr', {
	required: '...',
	// ...
});

setDefaultLang method can be used for setting default language .e.g. mitra.setDefaultLang('fr').

You can also use the third argument of the validate method:

mitra.validate(data, rules, 'fr');

The possible error messages of the above validation are generated by using the fr locale.

Adding Validators

mitra encourages creating a file for each validator. File should be created in a directory that has only validator files. Each file should export an object with following properties:

  • name Name of the validator. This property is not required as name of the validator is the actual name of the validator.
  • description Short description of the validator.
  • handler The validator handler. The handler is called with these arguments:
  • value Value that should be validated.
  • options Validator options.
  • key Attribute name.
  • message Default message for the validator.
  • attributes All user data that is passed to validate.

this value of the handler refers to mitra. Validators can call other validators by using the check method.

Validator must return a string for an invalid datum.

After creating validators, addValidators can be used for loading validator files. The method accepts one argument: path of validators directoy:

const path = require('path');
mitra.addValidators( path.join(__dirname, '../my_validators') );

Validators

array

checks: (any)
Value must be an array.

boolean

checks: (any)
Value must be a boolean value i.e. true or false.

confirmed

checks: (any)
Checks equality between 2 attributes' value, i.e. useful for checking password confirmation fields.

email

checks: (string)
Value should be a valid email address.

in

checks: (any)
Value must one of the allowed options.

integer

checks: (number)
Value (number) must be an integer.

max

checks: (number)
Value (number) should be equal or less than specified max value.

max_length

checks: (string, array)
Length of the value should be equal or less than specified maximum length.

min

checks: (undefined)
Value (number) should be equal or more than specified minimum value.

min_length

checks: (string, array)
Length of the value should be equal or more than specified minimum length.

null

checks: (any)
Value must be null.

number

checks: (any)
Value must be a number.

object

checks: (any)
Value must be a plain object.

range

checks: (number)
Value (number) must be in range, inclusive.

required

checks: (any)
Value must not be undefined, null, or an empty string!

required_if

checks: (any)
Element is required when another attribute is equal to the specified value.

string

checks: (any)
Value must be a string.

type

checks: (any)
Value must have one of the specified JavaScript types.

undefined

checks: (any)
Value must be undefined.

url

checks: (string)
Value must be a valid url.

License

MIT © Ram Hejazi