node-modules / parameter

A parameter verify tools.
Other
728 stars 118 forks source link

parameter

NPM version Node.js CI Test coverage npm download

A parameter verify tools.

Install

$ npm install parameter --save

Usage

API

Parameter Class

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.

Example

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

complex example

Rule

common rule

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:

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:

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:

Default convertType is string.

email

The email type want to match RFC 5322 email address.

Default convertType is string.

password

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

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:

object

If type is object, there has one addition rule:

array

If type is array, there has four addition rule:

abbr

errors examples

code: missing_field

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

code: invalid

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

License

MIT

Contributors


fengmk2


dead-horse


huacnlee


hotoo


sang4lv


ghostoy


beliefgp


taylorharwin


tomowang


hdumok


paranoidjk


zcxsythenew

This project follows the git-contributor spec, auto updated at Tue Apr 05 2022 10:44:22 GMT+0800.