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

@kodepandai/node-input-validator

v1.0.0-beta

Published

validation library for nodejs, inspired by laravel.

Downloads

44

Readme

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

  • jgnovais

Roadblock

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