mitra

1.2.0 • Public • Published

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: 'philonoid@hell.com',
  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

Package Sidebar

Install

npm i mitra

Weekly Downloads

1

Version

1.2.0

License

MIT

Unpacked Size

30.1 kB

Total Files

31

Last publish

Collaborators

  • ramhejazi