当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

node-input-validator

Validation library for node.js
授权协议 Readme
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 封鸿雪
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Validation Library

Validation library for node.js

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 rule behaviour.

Installation

npm i node-input-validator

Features

  • large collection of rules
  • add your own 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

Simple Example

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

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

v.check().then(function (matched) {
  console.log(matched);
  console.log(v.errors);
});

With in express application

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

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

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

With async-await

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

router.post('login', async (ctx) => {
  const v = new Validator(ctx.request.body, {
    email: 'required|email',
    password: 'required'
  });

  const matched = await v.check();

  if (!matched) {
    ctx.status = 422;
    ctx.body = v.errors;
    return;
  }
});

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

// 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);

// 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

// if validation fails, this will auto abort request with status code 422 and errors in body
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
This method (ctx.validator(inputs, rules, messages={})) also support same options as like ctx.validate

Objects Validation

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.check();

Array Validation

Example 1

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

let matched = await v.check();

Example 2

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

Add or Modify messages

Placeholder in messages, :attribute will be replaced with field/attribute name, :value with field value and :arg0, :arg1 ...n with arguments passed to rule.

Add/Update rule based messages

const niv = require('node-input-validator');
/**
 * @param {Object} messages
 * @param {string?=en} language
 */
niv.extendMessages({
  required: 'The :attribute field must not be empty.',
  email: 'E-mail must be a valid email address.',
  even: 'The value of the field must be even number.',
  status: 'Invalid status'
}, 'en');

Add custom messages

const niv = require('node-input-validator');
//Note: Default language is English (en).
niv.addCustomMessages({
  'username.required': 'When username attribute required rule failed.',
  username: 'Default message for username attribute.'
});

for message in another language

You can easliy add messages in another language.

const niv = require('node-input-validator');
niv.extendMessages({
  required: ':attribute ਫੀਲਡ ਖਾਲੀ ਨਹੀਂ ਹੋਣਾ ਚਾਹੀਦਾ.',
}, 'pb');

Set default language

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

Toggle Multiple Errors Support

By default, Validator will run in bailable mode ie. break if some rule failed. You can change this behaviour:

Globally

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

Now instead of breaking, it will continues apply other rules.

Errors example

{
  name: [
    {
      rule: 'minLength',
      message: '...',
    },
    {
      rule: 'alpha',
      message: '...',
    }
  ]
}

Locally

To toggle multiple errors on specific instance only.

const niv = require('node-input-validator');
const v = new niv.Validator(inputs, rules);
v.bail(false);

Set attribute nice/custom name

You can also declare Nice Names / Custom Attributes names.

const niv = require('node-input-validator');
niv.niceNames({
  phone: 'phone number',
  dob: 'Date of Birth'
});

If your are editing other languages, set lang parameter.

const niv = require('node-input-validator');
niv.niceNames({
  phone: 'phone number',
  dob: 'Date of Birth'
},'fa');

In error messages you will get "phone number" instead of phone. For Example: In case required rule failed, Error message will be: The phone number field is mandatory.

For current instance only

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

const v = new niv.Validator(inputs, rules);
v.niceNames({
  phone: 'phone number',
  dob: 'Date of Birth'
});

This will only change attribute names for current instance.

Add your own custom validation rules

// second params will be the instance of Validator
niv.extend('even', ({ value }) => {
  if ((parseInt(value) % 2) == 0) {
    return true;
  }
  return false;
});

Example of using other fields in rule

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

niv.extend('sumOfFields', ({ value, args }, validator) => {
  if (args.length !== 2) {
    throw new Error('Invalid seed for rule sumOfFields');
  }

  const anotherValue = Number(validator.inputs[args[0]]);

  const eq = Number(args[1]);

  if ((Number(value) + anotherValue) !== eq) {
    return false;
  }

  return true;
});

let v = new niv.Validator(
  { num1: '50', num2: '50' },
  { num1: 'sumOfFields:num2,100|required' },
);

let matched = await v.check();

assert.equal(matched, true);

Example of using async rules

// use this rules as unique:seed
// unique:<Mongoose Model>,<Field Name>,<ID to Ignore, This is optional>

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

niv.extend('unique', async ({ value, args }) => {
  // default field is email in this example
  const field = args[1] || 'email';

  let condition = {};

  condition[field] = value;

  // add ignore condition
  if (args[2]) {
    condition['_id'] = { $ne: mongoose.Types.ObjectId(args[2]) };
  }

  let emailExist = await mongoose.model(args[0]).findOne(condition).select(field);

  // email already exists
  if (emailExist) {
    return false;
  }

  return true;
});

// example usage of upper extended rule

new niv.Validator({
  email: 'required|email|unique:User,email'
}, inputs);

// in case to ignore specific id

new niv.Validator({
  email: 'required|email|unique:User,email,5c2f29e9cefa7718a54f8ff1'
}, inputs);

Example of using rules as array

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

let v = new niv.Validator(
  { foo: 'bar'},
  { foo: ['required', 'string', ["minLength", 5]] },
);

let matched = await v.check();

assert.equal(matched, true);

v = new niv.Validator(
  { foo: 'bar'},
  { foo: ['required', 'string', "minLength:5" ] },
);

matched = await v.check();

assert.equal(matched, true);

Rules

You can check test cases for rule usage/examples.

required
The field under validation cannot be left blank.

// should fail
new Validator(
  { name: '' },
  { name: 'required' },
);

requiredIf:field,value
The field under validation cannot be left blank, if provided seed value equals to provided value seed.

// requiredIf rule validation fails, becoz email cannot be left blank if age is 16
new Validator(
  { email: '', age: '16' },
  { email: 'requiredIf:age,16' },
);

requiredNotIf:field,value
The field under validation may left blank, if provided seed value equals to provided value seed.

// requiredNotIf rule validation fails, becoz transport must be present in case age is not 16
new Validator(
  { transport: '', age: '15' },
  { transport: 'requiredNotIf:age,16' },
);

requiredWith:field
requiredWith:field,field,field
The field under validation may required in case provided seed present.

// requiredWith rule validation fails, becoz email must in case age present.
new Validator(
  { email: '', age: '17' },
  { email: 'requiredWith:age' },
);

requiredWithout:field
requiredWithout:field,field,field
The field under validation may left blank in case provided seed present.

// requiredWithout rule validation fails, becoz email is must in case phone,pan not provided.
new Validator(
  { email: '', username: '' },
  { email: 'requiredWithout:phone,pan', username: 'requiredWithout:email' },
);

accepted
The field under validation must be yes, on, 1, or true.

accepted:seeds
The field under validation must be accepted if value exists in provided seed.

after:YYYY-MM-DD
The field under validation must be date after provided seed.

new Validator(
  { joining: '' },
  { joining: 'required|after:2018-02-10' },
);

alpha
alpha:locale
The field under validation must be entirely alphabetic characters.

alphaDash
The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alphaNumeric
alphaNumeric:localeThe field under validation only contains letters and numbers.

array
The field under validation must be an array.

arrayUnique
Added in: v3.5
The field under validation must be an array and must contains unique values. No need to use array rule. This rule will take care of that.

arrayUniqueObjects:attributes
Added in: v3.5
The field under validation must be an array and should have objects with unique attributes as per seed. No need to use array rule. This rule will take care of that.

ascii
The field under validation only contains ascii characters.

base64
The field under validation must be valid base64 encoded string.

between:min,max
The field under validation must be betwwen min and max seed. This will work with number valus as well as with arrays using array count.

boolean
boolean:custom
The field under validation must be boolean (true, false, 'true', 'false', 0, 1, '0', '1') or in custom seed.

contains:value
The field under validation must contains provided seeds.

let v = new Validator({bio:'My profile is: example.com'}, {bio:'required|contains:profile'});

creditCard
The field under validation must be valid credit card string.

date
The field under validation must be a valid date (YYYY-MM-DD).

dateAfterToday:number,unit
The field under validation must be a valid date after provided seed.

new Validator(
  { expiry: '2019-02-28' },
  { expiry: 'required|dateAfterToday:2,days' },
);

see moment docs(https://momentjs.com/docs/#/manipulating/add/) for supported units.

dateBeforeToday:number,unit
The field under validation must be a valid date before provided seed.

let v = new Validator({valid:'2019-02-28'}, {valid:'required|dateBeforeToday:2,months'});

dateFormat:format
The field under validation must match the given date format.

Note: use array of rules style declaration to deal with colon (:) in time formats.

new Validator(
  { dob: '' },
  { dob: 'required|dateFormat:YYYY-MM-DD' },
);

Check https://momentjs.com/docs/ for supported formats

dateiso
Added in: v3.6
The field under validation must be a valid iso date.

datetime
Added in: v3.6
The field under validation must match YYYY-MM-DD HH����ss format.

decimal
The field under validation must be a decimal value.

digits:length
The field under validation must be numeric and must have an exact length.

digitsBetween:min,max
The field under validation must have a length between provided min and max values.

domain
The field under validation must a qualified domain.

dimensions:seed
Added in: v3.7
The image under validation must meet the dimension constraints as specified by in seed.

new Validator(
  req.body,
  { file: 'dimensions:minWidth=50,minHeight=50' },
);

const matched = await v.check();

assert.equal(matched, false);

Note: image mimes validation is required before.

Available constraints are: minWidth, maxWidth, minHeight, maxHeight, width, height.

email
The field under validation must be formatted as an e-mail address.

equals
The field under validation must be equal to given value.

gt:another_field
Added in: v3.4
The field under validation must be greater then another field value. This rule is for Numbers comparision.

gte:another_field
Added in: v3.4
The field under validation must be greater or equals to another field value. This rule is for Numbers comparision.

hash:algo
The field under validation must be a valid hash as per provided seed.

new Validator(
  {
    id: 'fd1baf48377a9f644f9af89abbee29f6'
  },
  {
    id: 'required|hash:md5'
  },
);

Supported algorithms: md4, md5, sha1, sha256, sha384, sha512, ripemd128, ripemd160, tiger128, tiger160, tiger192, crc32, crc32b.

hex
The field under validation must be valid hex.

hexColor
The field under validation must be valid hex color code.

in:a,b...n
The field under validation must exist in the given list of values.

new Validator(
  { status: '' },
  { status: 'required|in:active,inactive,blocked' },
);

integer
The field under validation must be an integer.

ip
The field under validation must be an IP address.

iso8601
The field under validation must be valid Iso8601 date.

json
The field under validation must be a valid JSON string.

length:max
length:max,min
Added in: v3.5
The field under validation must be less then or equals to max seed provided in rule. In case of min,max seed, field under validation must be less or equals to max seed and less then min seed. Can only be used with strings|arrays or any other object that supports length (str.length) property.

latLong
The field under validation must be a valid latitude-longitude coordinate.

lengthBetween:min,max
The field under validation value length must be between provided values.

let v = new Validator({age:''}, {age:'required|between:17,30'});

lt:another_field
Added in: v3.4
The field under validation must be less then another field value. This rule is for Numbers comparision.

lte:another_field
Added in: v3.4
The field under validation must be less or equals to another field value. This rule is for Numbers comparision.

macAddress
The field under validation should be a valid Mac Address.

max:seed
The field under validation must be less than given value.

new Validator(
  { age: '' },
  { age: 'required|max:35' },
);

maxLength:seed
The length of field under validation should be less than given value.

new Validator(
  { username: '' },
  { username: 'required|max:10' },
);

mime:seed
The file under validation must have a MIME type corresponding to one of the listed extensions.

new Validator(
  req.body,
  { file: 'required|mime:jpg,png' },
);

min
The field under validation must be greater than given value.

minLength
The length of field under validation should be greater than given value.

mongoId
The field under validation should be a valid MongoDB ID.

notContains:seed
The field under validation may not contains provided seeds.

notIn:seeds
The field under validation must not exist in the given list of values.

nullable
The field under validation is required only is not left empty.

numeric
The field under validation must be numeric.

phoneNumber
The field under validation must be a valid phone number.

regex
The field under validation must match the given regular expression.

Note: Currently regex rules break on using colon (:) or pipe delimiters. Use array of rules style declaration instead of string.

new Validator(
  req.body,
  { username: ['required', 'regex:[a-z]'] },
  { password: 'required|same:confirm_password' },
);

same
The given field must match the field under validation.

size:max
size:max,min
The file field under validation must have a file size matching the given maximum value or should be between size range.Supported unit sufix: b(Bytes),kb/k(KilloBytes),mb/m(MegaBytes),gb/g(GigaBytes).

// in below case, image file size should be under 4kb limit
new Validator({image:''}, {image:'required|size:4kb'});
// in below case, image file size should be between 1kb - 4kb
new Validator({image:''}, {image:'required|size:4kb,1kb'});
new Validator({video:''}, {video:'required|size:10mb'});

sometimes
The field under validation is required if present.

string
The field under validation must be string.

url
The field under validation must be a valid URL.

Post Rules
There is set of rules which can be used to validate constraints of whole input, rather than validity of singular fields.

const v = new Validator(
  { name: '' },
  { '*': 'any:name,surname' },
);

v.check().then(function (matched) {
  console.log(matched);
  console.log(v.errors);
});

Post validator errors are returned in the * key. There is also possibility to add custom function as validatorwith help of addPostRule method. Function will be called in context of validator object with input as parameter.

const v = new Validator(
  { username: 'arnold', password: 'arnold123' },
  { username: 'required', password: 'required' },
);

v.addPostRule((provider) => {
  if (provider.inputs.password.indexOf(provider.inputs.username) >= 0) {
    provider.error('password', 'custom', 'Password cannot contain username');
  }
});

any
Any of the fields must be present in input.

all
All of the fields must be present in input.

Typescript Support

Partial Support.

  • 我是新来的节点,当用户尝试提交表单时,尝试显示验证错误(使用express-validator和express 4)。node/express 4:在ajax post上使用express-validator显示错误 验证程序似乎工作,因为如果我将数据记录到控制台,一切都如预期。但是,当我渲染视图时,无法在页面上显示错误(不显示任何内容)。与我一直在进行快速验证的“标准”教程唯一的区别是,我使用A

  • 提交表单的时候,前端验证都可以绕过,这个时候就需要后端验证了,本文就是介绍的nodejs后端的验证模块,validator -- 安装模块 npm install validator 引入 var validator = require('validator'); -- 验证介绍 contains(str, seed) : 是否包含字符串 equals(str, comparison) : 检查字

  • <template> <div :class="[ type === 'textarea' ? 'el-textarea' : 'el-input', inputSize ? 'el-input--' + inputSize : '', { 'is-disabled': inputDisabled, 'is-exceed': inputExcee

  •   Vue Webpack Node npm cnpm的关系理解: 1.实际上Vue本身是不依赖Node的, 2.而Vue-cli的脚手架是依赖于Webpack的,所以间接的也需要Node的支持, 3.Webpack基于Node的运行环境,Webpack在执行打包压缩的时候依赖Node, 没有Node就不能使用Webpack,并且支持ES6 4.npm只是nodejs的一个模块,运行在Node上,

 相关资料
  • 等待用户输入字符串。 Input [, OutputVar, Options, EndKeys, MatchList] 参数 OutputVar 用来保存用户输入文本的变量名 (默认情况下, 模拟输入也被保存下来). 如果省略此参数和其他参数, 那么会终止在其他 线程 中正在执行的任何 Input 并且将那个 Input 的 ErrorLevel 设置为单词 NewInput. 与之相比, 如果终

  • ion-input拥有很多文本类型,例如:text password email number search tel 和 url。

  • 简介 Weex 内置的 <input> 组件用来创建接收用户输入字符的输入组件。 <input> 组件的工作方式因 type 属性的值而异,比如 text, password,url,email,tel 等。 注意 此组件不支持 click 事件。请监听 input 或 change 来代替 click 事件。 子组件 <input> 不支持子组件。 属性 key 类型 描述 默认值 备注 typ

  • 1.5.0 新增 输入框组件。支持使用v-model对数据双向绑定,支持一键清空内容。 示例 基本用法 使用v-model对输入内容双向绑定。 <cube-input v-model="value" ></cube-input> export default { data() { return { value: '' } } } 控制最大长度 通过 watc

  • INPUT #iptables --line-numbers -vnL INPUTChain INPUT (policy ACCEPT 0 packets, 0 bytes)num pkts bytes target prot opt in out source destination1 360K 56M neutron-open

  • input 输入框。 当点击 <form/> 表单中 formType 为 submit 的 <button/> 组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。 属性名 类型 默认值 说明 value String 输入框的初始内容 type String "text" input 的类型 password Boolean false 是否是密码