@kodepandai/node-input-validator
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-beta • Public • Published

NIV (Node Input Validator)

NPM version build status known vulnerabilities codecov.io Status david node version

NIV (Node Input Validator) is a validation library for node.js. You can also extend library to add custom rules.

Note: For use case of any rule, please check test cases, If you have any doubt or confusion with documentation or regarding rule behaviour.

Installation

npm i node-input-validator@v5

This library supports both cjs and esm.

Using CJS

const { Validator } = require('node-input-validator');

Using ESM

import { Validator } from 'node-input-validator';

Documentation

For detailed documentation, see https://bitnbytes.io/docs/niv/index.html

Features

  • typescript compatible
  • large collection of rules
  • add custom rules
  • supports nested inputs
  • declare rules as strings or array
  • post validation rules
  • modify or add new messages in your own language
  • change attribute names globally or locally
  • current supported languages: English, Persian(farsi)

Usage

Basic Example

Vanila Javascript

Style 1
const { Validator, Rules } = require('node-input-validator');

const v = new Validator(
  { name: '' },
  { name: 'required|alpha' },
);

v.validate().then((passed) => {
  console.log(passed);

  if (!passed) {
    console.log(v.getErrors());
  }
});
Style 2
const { Validator, Rules } = require('node-input-validator');

const v = new Validator(
  { name: '' },
  { name: ['required', 'alpha'] },
);

v.validate().then(function (passed) {
  console.log(passed);
  console.log(v.errors);
});
Style 3
const { Validator, Rules } = require('node-input-validator');

const v = new Validator(
  { name: '' },
  { name: [Rules.required(), Rules.alpha()] },
);

v.validate().then(function (passed) {
  console.log(passed);
  console.log(v.errors);
});

async/await

const { Validator, Rules } = require('node-input-validator');

const v = new Validator(
  { name: '' },
  { name: [Rules.required(), Rules.alpha()] },
);

const passed = await v.validate()
console.log(passed);
console.log(v.errors);

Typescript

import { Validator, Rules } from 'node-input-validator';

const v: Validator = new Validator(
  { name: '' },
  { name: [Rules.required()] },
);

const passed: boolean = await v.validate();

console.log(passed);
console.log(v.errors);

For Koa2

Attach koa middleware

const niv = require('node-input-validator');

// keep this under your error handler
app.use(niv.koa());

Then in controller

// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
  name: 'required|maxLength:50',
  username: 'required|maxLength:15',
  email: 'required|email',
  password: 'required'
});

// validation passes
// do some code

With custom inputs

const cutomInputs = {...}

// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
  name: 'required|maxLength:50',
  username: 'required|maxLength:15',
  email: 'required|email',
  password: 'required'
}, cutomInputs);

// validation passes
// do some code

With custom inputs and custom messages

// if validation fails, this will auto abort request with status code 422 and errors in body
await ctx.validate({
  name: 'required|maxLength:50',
  username: 'required|maxLength:15',
  email: 'required|email',
  password: 'required'
}, ctx.request.body, { email: 'E-mail is required' });

// validation passes
// do some code

In case you wants control over validator, Then use

const v = await ctx.validator(ctx.request.body, {
  name: 'required|maxLength:50',
  username: 'required|maxLength:15',
  email: 'required|email',
  password: 'required'
});

// in case validation fails
if (v.fails()) {
  ctx.status = 422;
  ctx.body = v.errors;
  return;
}

// do some code

with express

const { Validator } = require('node-input-validator');

app.post('login', function (req, res) {
  const v = new Validator(req.body, {
    email: 'required|email',
    password: 'required'
  });

  v.validate().then((matched) => {
    if (!matched) {
      res.status(422).send(v.errors);
    }
  });
});

Validate objects

Example 1

const v = new Validator(
  {
    product: {
      id: '1',
      name: '',
      price: '',
      active: 'yes',
    }
  },
  {
    'product': 'required|object',
    'product.id': 'required|integer',
    'product.name': 'required',
    'product.price': 'required|integer',
    'product.active': 'required|integer'
  },
);

const matched = await v.validate();

Validate Array

Example 1

let v = new Validator(
  {
    roles: ['admin', 'manager', 'member']
  },
  {
    'roles': 'required|array',
    'roles.*': 'required|string'
  },
);

const matched = await v.validate();

Example 2

let v = new Validator(
  {
    plans: [
      { price: '25', title: 'OK' },
      { price: '', title: '' },
      { price: '30' },
      { price: '', title: 'Title' }
    ]
  },
  {
    'plans': 'required|array',
    'plans.*.price': 'required|integer',
    'plans.*.title': 'required'
  },
);

const matched = await v.validate();

Add custom rules

const niv = require('node-input-validator');

niv.extend('even', () => {
  return {
    name: 'even',
    handler: (v) => v % 2,
  }
});

// Add message for your rule
niv.Messages.extend({
  even: 'The :attr value must be an even number.',
  required: 'The attribute is required.',
})

Add/Modify messages

// modify existing rule message
niv.Messages.extend({
  required: 'The attribute is required.',
});

// add custom message on required rule for name
niv.Messages.addCustomMessages({
  'name.required': 'The name is required.',
});

// or no matter what the rule is use common message for name
niv.Messages.addCustomMessages({
  name: 'The name is malformed.',
});

Set Nicenames

Set nicenames globally

// email in error message will be replaced with E-mail
niv.Messages.addNiceNames({
  email: 'E-mail',
});

Set nicenames locally

const { Validator } = require('node-input-validator');

const v = new Validator(
  {},
  {
    email: 'required|email',
  },
)

// this will only replace email with E-mail for error message of this instance
v.niceNames({
  email: 'E-mail',
});

v.validate()

Date Rules

To use date rules, you has to install moment or date-fns

For moment

const { MomentAdapter, useDateAdapter  } = require('node-input-validator');
const moment = require('moment');

useDateAdapter(new MomentAdapter(moment));

For date-fns

const { DateFnsAdapter, useDateAdapter  } = require('node-input-validator');
const dateFns = require('date-fns');

useDateAdapter(new DateFnsAdapter(dateFns));

using validator

To use validator rules, first your need to install it

npm i validator

Example 1

Then your can use all rules of validator.js as sub rule under rule validator.

const { Validator } = require('node-input-validator');

const v = new Validator(
  {},
  {
    email: 'validator:isEmail',
  },
)

v.validate()

Example 2

Passing arguments to validator.js rules, example passing locale to isAlpha rule.

const { Validator } = require('node-input-validator');

const v = new Validator(
  req.body,
  {
    email: 'validator:isAlpha,pt-BR',
  },
)

v.validate()

Example 3

const { Validator, Rules } = require('node-input-validator');

const v = new Validator(
  req.body,
  {
    email: [Rules.validator('isAlpha', ['pt-BR'])],
  },
)

v.validate()

Note: You have to manually add messages for most validator.js rules.

How package check messages for validator.js

Package internaly remove "is" from validator.js rule and make it lowercase.

For example: isEmail -> email, hence it can use existing email message.

Rules

For rules documentation, see https://bitnbytes.io/docs/niv/modules/rules.html

Many thanks

Roadblock

  • fillMissingSpots overwriting array value in nested inputs, eg. product.attributes..colors.

Package Sidebar

Install

npm i @kodepandai/node-input-validator

Weekly Downloads

10

Version

1.0.0-beta

License

ISC

Unpacked Size

230 kB

Total Files

75

Last publish

Collaborators

  • axmad386