Parameter 一个轻量的 Node.js 数据验证工具

简介:

一个轻量级的参数验证工具,国人开发,非常符合我的口味。


安装:

npm install parameter --save


使用方法:

constructor([options]) - new Class Parameter instance

options.translate - translate function

options.validateRoot - config whether to validate the passed in value must be a object, default to false.

options.convert - convert primitive params to specific type, default to false.

options.widelyUndefined - convert empty string(''), NaN, Null to undefined, this option can make rule.required more powerful, default to false.This may change the original input params.

validate(rule, value) - validate the value conforms to rule. return an array of errors if break rule.

addRule(type, check) - add custom rules.

type - rule type, required and must be string type.

check - check handler. can be a function or a RegExp.

Note: when options.convert enabled, all built-in rules check for primitive input param and convert it to rule's default convertType(which defined below), you can also enable this feature for specific rule by convertType options in each rule definition.


使用方法:

var Parameter = require('parameter');

var parameter = new Parameter({
 translate: function() {
  var args = Array.prototype.slice.call(arguments);
  // Assume there have I18n.t method for convert language.
  return I18n.t.apply(I18n, args);
 },
 validateRoot: true, // restrict the being validate value must be a object
});

var data = {
 name: 'foo',
 age: 24,
 gender: 'male'
};

var rule = {
 name: 'string',
 age: 'int',
 gender: ['male', 'female', 'unknown']
};

var errors = parameter.validate(rule, data);


复杂一点的例子

var Parameter = require('./');

var rule = {
 name: 'string',
 age: {type: 'int', max: 200},
 gender: ['male', 'female'],
 working: 'boolean',
 salary: {type: 'number', min: 0},
 birthday: 'date',
 now: 'dateTime',
 id: 'id',
 childrens: {
  type: 'array',
  itemType: 'object',
  required: false,
  rule: {
   name: 'string',
   age: 'int',
   gender: ['male', 'female'],
   birthday: {type: 'date', required: false}
  }
 },
 mate: {
  type: 'object',
  required: false,
  rule: {
   name: 'string',
   age: 'int',
   gender: ['male', 'female'],
   birthday: {type: 'date', required: false}
  }
 }
};

var valid = {
 name: 'foo',
 gender: 'male',
 age: 30,
 working: true,
 salary: 10000.1,
 birthday: '1990-01-01',
 now: '2015-01-07 00:00:00',
 id: '052111',
 childrens: [{
  name: 'bar1',
  age: 1,
  gender: 'female',
  birthday: '2014-01-01'
 }, {
  name: 'bar2',
  age: 2,
  gender: 'male',
  birthday: '2013-01-01'
 }],
 mate: {
  name: 'hee',
  age: 29,
  gender: 'female'
 }
};

var invalid = {
 name: 1,
 gender: 'male1',
 age: 300,
 working: 'true',
 salary: '10000.1',
 birthday: '1990-01-011',
 id: '052111x',
 childrens: [{
  name: 'bar1',
  gender: 'female',
  birthday: '2014-01-01'
 }, {
  name: 'bar2',
  age: 2,
  birthday: '2013-01-01'
 }],
 mate: {
  age: 29,
  gender: 'female'
 }
};

var p = new Parameter();

console.log('valid object result: ', p.validate(rule, valid));
console.log('invalid object result: ', p.validate(rule, invalid));



验证规则

common rule

required - if required is set to false, this property can be null or undefined. default to true.

type - The type of property, every type has it's own rule for the validate.

convertType - Make parameter convert the input param to the specific type, support int, number, string and boolean, also support a function to customize your own convert method.

default - The default value of property, once the property is allowed non-required and missed, parameter will use this as the default value. This may change the original input params.

widelyUndefined - override options.widelyUndefined

Note: you can combile require and type end with a notation ? like: int? or string? to specific both type and non-required.


int

If type is int, there has tow addition rules:


max - The maximum of the value, value must <= max.

min - The minimum of the value, value must >= min.

Default convertType is int.


Note: default convertType will only work when options.convert set to true in parameter's constructor.


integer

Alias to int.


number

If type is number, there has tow addition rules:


max - The maximum of the value, value must <= max.

min - The minimum of the value, value must >= min.

Default convertType is number.


date

The date type want to match YYYY-MM-DD type date string.


Default convertType is string.


dateTime

The dateTime type want to match YYYY-MM-DD HH:mm:ss type date string.


Default convertType is string.


datetime

Alias to dateTime.


id

The id type want to match /^\d+$/ type date string.


Default convertType is string.


boolean

Match boolean type value.


Default convertType is boolean.


bool

Alias to boolean


string

If type is string, there has four addition rules:


allowEmpty(alias to empty) - allow empty string, default to false. If rule.required set to false, allowEmpty will be set to true by default.

format - A RegExp to check string's format.

max - The maximum length of the string.

min - The minimum length of the string.

trim - Trim the string before check, default is false.

Default convertType is string.


email

The email type want to match RFC 5322 email address.


allowEmpty - allow empty string, default is false.

Default convertType is string.


password

The password type want to match /^$/ type string.


compare - Compare field to check equal, default null, not check.

max - The maximum length of the password.

min - The minimum length of the password, default is 6.

Default convertType is string.


url

The url type want to match web url.


Default convertType is string.


enum

If type is enum, it requires an addition rule:


values - An array of data, value must be one on them. this rule is required.

object

If type is object, there has one addition rule:


rule - An object that validate the properties ot the object.

array

If type is array, there has four addition rule:


itemType - The type of every item in this array.

rule - An object that validate the items of the array. Only work with itemType.

max - The maximun length of the array.

min - The minimun lenght of the array.

abbr

'int' => {type: 'int', required: true}

'int?' => {type: 'int', required: false }

'integer' => {type: 'integer', required: true}

'number' => {type: 'number', required: true}

'date' => {type: 'date', required: true}

'dateTime' => {type: 'dateTime', required: true}

'id' => {type: 'id', required: true}

'boolean' => {type: 'boolean', required: true}

'bool' => {type: 'bool', required: true}

'string' => {type: 'string', required: true, allowEmpty: false}

'string?' => {type: 'string', required: false, allowEmpty: true}

'email' => {type: 'email', required: true, allowEmpty: false, format: EMAIL_RE}

'password' => {type: 'password', required: true, allowEmpty: false, format: PASSWORD_RE, min: 6}

'object' => {type: 'object', required: true}

'array' => {type: 'array', required: true}

[1, 2] => {type: 'enum', values: [1, 2]}

/\d+/ => {type: 'string', required: true, allowEmpty: false, format: /\d+/}

errors examples

code: missing_field

{
 code: 'missing_field',
 field: 'name',
 message: 'required'
}

code: invalid

{
 code: 'invalid',
 field: 'age',
 message: 'should be an integer'
}

Release process

We're using semantic-release to run npm publish after every commit on master.




参考:

https://github.com/node-modules/parameter

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
MySQL 使用 DATE_FORMAT() 和 FROM_UNIXTIME() 格式化时间
Node.js MySQL 连接池和事务
支持 Selector API 的 HTML 解析器 node-html-parser
WordPress 密码生成和密码验证
wp_signon() 自定义用户登录函数
Node.js readline 模块
CSS 滚动条样式修改
HTML input range 数值范围选择器