Giter Site home page Giter Site logo

parameter's Introduction

parameter

NPM version Node.js CI Test coverage npm download

A parameter verify tools.

Install

$ npm install parameter --save

Usage

API

Parameter Class

  • 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.

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

Rule

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.
    /**
     * check array
     * {
     *   type: 'array',
     *   itemType: 'string'
     *   rule: {type: 'string', allowEmpty: true}
     * }
     *
     * {
     *   type: 'array'.
     *   itemType: 'object',
     *   rule: {
     *     name: 'string'
     *   }
     * }
     */
  • max - The maximum length of the array.
  • min - The minimum 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'
}

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.

parameter's People

Contributors

4xii avatar beliefgp avatar dead-horse avatar fengmk2 avatar ghostoy avatar hdumok avatar hotoo avatar huacnlee avatar paranoidjk avatar sang4lv avatar sarike avatar semantic-release-bot avatar taylorharwin avatar tomowang avatar zcxsythenew avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

parameter's Issues

[Feature request] Remove not permitted attributes

I would be great to have the ability to remove not permitted attributes. For example:

const params = { age: 25, foo: "bar" }
const rules = { age: { type: "int", max: 200 } }
const errors = parameter.validate(rules, params)

make params to be equal to {age: 25}, not to {age: 25, foo: "bar"}.

合法值自定义过滤方法

比如在检索字符串模糊查询的时候,输入/\字符,则会破坏正则表达式,是否可以在校验的时候添加一个自定义过滤的方法解决这样的问题呢?

验证邮箱可以为空时错误

例如:

var data = {
  mail: ''
};

var rule = {
  mail: {
    required: false,
    allowEmpty: true,
    type: 'email'
  }
};

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

这个时候会验证失败

Can't validate Array

const arr = [{ key: ' ' }];
const rules = {};
validate(rules, arr);

No matter how to set the rule can not validate the array

对于一个已存在的值,需要置空,如何传参

例如用户预约日期字段,用户原先选择了一个日期,保存成功。
后来用户想暂时移除该日期,于是删除了选择的日期,此时前端将该字段以 NULL 形式告知后端,该字段已被删除。
但此时 parameter 做校验时,即使标识了 required = false, allowEmpty = true,仍然会报错。

One Of 是否支持呢

假设 我有两个字段, 只需要存在其中一个字段即可.
这个怎么去写 Rule.

support custom rule type plugins

parameter.addRule({
  type: 'email',
  format: /^\w+@\w+$/
});

parameter.addRule({
  type: 'password',
  check: function (value, ruleConfig, obj) {
    if (value !== obj[ruleConfig.compare]) {
       return 'should equal to ' + ruleConfig.compare;
    }
  }
});

How to config `required` defaultValue ?

The docs describe the required default to true, but for my project, the conditions required false are more than true.

May provide a config like :

var parameter = new Parameter({
  defaultRequired: false, 
});

Trying to get in touch regarding a security issue

Hey there!

I'd like to report a security issue but cannot find contact instructions on your repository.

If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

Thank you for your consideration, and I look forward to hearing from you!

(cc @huntr-helper)

email验证是不是存在BUG

const Parameter = require('parameter');
var parameter = new Parameter({
translate: function() {

var args = Array.prototype.slice.call(arguments);
console.log(args);

},
validateRoot: true, // restrict the being validate value must be a object
});
var data = {
name: 'yong',
age: 12,
gender: 'male',
email: '[email protected]'
};

var rule = {
name: 'string',
age: {type:'int', max: 150, min: 0},
gender: ['male', 'female', 'unknown'],
email: {type:'email', format: Parameter.EMAIL_RE}
};

var errors = parameter.validate(rule, data);
if(errors)
console.log(errors);
email正确的情况下,为什么translate函数中还要打印出[ 'should be an email' ]
另外,什么时候能够支持手机号码验证?

可以用typescript的interface来设置rule

一般写ts的时候会先申明一个interface(这个interface只能够解决ts编译前的校验),可以利用这个interface来生成rule,校验运行时的参数,比如对一个request做参数校验:

interface ParamRequest {
  id: number,
  page: string,
  hehe: boolean,
  haha: Array<string>,
}

let rule: ParamRequest;

const param: ParamRequest = this.request.body;

const isError = this.validate.validator(rule,  param);

addRule readme需要详细点

addRule,完全不知道check作为fun的时候是否对返回值有要求,什么情况下是验证通过,什么情况下是验证不通过

int 验证规则有问题

验证数据类型为 int ,
当POST提交的数据为 aa , 验证不通过
当POST提交的数据为 aa123 , 验证不通过
当POST提交的数据为 123aa , 验证通过

这是不是属于个 bug

const {ctx}=this; let rules={ fdate:{type:'string'}, fdept:{type:'int'}, fid:{type:'string'}, }; try{ ctx.validate(rules,ctx.request.body); }catch(err){ ctx.body={ code: -1, msg: err }; return; }

自定义校验如何使用

不好意思,实在没看明白自定义规则如何使用。
const rule = { title: 'myRule' };
let r = ctx.validate(rule, ctx.request.body);
r 一直是undefined

Support Enum

{
  unit: ['y', 'w', 'd', 'm']
}

// or

{
  unit: { type: ['y', 'w', 'd', 'm'], required: false, empty: true }
}

无法自定义message?

不支持自定义message,请参考https://github.com/jzaefferer/jquery-validation ,很多时候messages节点内提示的文案内容是自定义的

const loginRule = {
    rules: {
        username: {
            type: 'email'
        },
        password: {
            required: true
        }
    },
    messages: {
        username: {
            required: "请输入用户名.",
            email: "请输入正确的邮箱格式"
        },
        password: {
            required: "请输入如密码."
        },
    }
};

合法的url check不通过

待测试的url:

"long_url": "http://jice.io?utm_campaign=123",

测试结果:

image

试了下把参数的的部分,?前面加上/就可以通过。

修改后的url:

"long_url": "http://jice.io/?utm_campaign=123",

结果: OK

{required: false} rule does not skip the validation when the value is undefined but the key exists in the object

Related issue: #25 (in chinese).

Use case:

const obj = {test: null};

parameter.validate({
    test: {
        type: "integer",
        required: false
    }
}, obj);

The above code will give the error should be an integer even if the required: false rule is defined.

Where is the problem:
https://github.com/node-modules/parameter/blob/master/index.js, row 61 to 63

var has = obj.hasOwnProperty(key);

if (!has) {

This condition should be replaced with:

var rule = formatRule(rules[key]);
var value = obj[key];

if (value == undefined) {
    if (rule.required) {
        /* push required error */
    }
    continue;
}

有多余的参数不会抛出异常

example

`
var Rule = {
name: { type: 'string' },
password: { type: 'string' },
};

var shouldThrowError = {
"name":"test",
"password":"test",
"password2":"test"
}
`

实际上会验证成功,至少应该有可以配置不能有多余参数的配置

How to add rule check uuid

I need check param is uuid, but lib not support.

My example code:

var data = {
  id: '1b671a64-40d5-491e-99b0-da01ff1f3341',
  name: 'foo',
  age: 24,
  gender: 'male'
};

var rule = {
  id: 'uuid',  // need support
  name: 'string',
  age: 'int',
  gender: ['male', 'female', 'unknown']
};

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

i think it support in next version.

tks so much

该项目是否还有人维护呢

npm install 提示栈溢出,应该是环境出错,验证环境应该修复,现在想要新增一些新功能,或者修复原有bug都无法做到
image

希望增加 global option matches: true || false, 用来控制是否强制匹配属性,生成Error报错或者自动删除Rule里不存在的属性

example:
const rule = {
  username: 'string',
  token: 'string',
  role: 'string',
  attributes: 'object',
  offset: {
      delete: true,
  },
  count: 'int',
};
let params = {
  username: 'username',
  token: 'token',
  role: 'role',
  attributes: 'attributes',
  offset: 'offset',
  count: 'count',
  count1: 'count1',
}
console.log(validate(rule, params));
console.log(delete(rule, params));
out:
false || Error();
{
  username: 'username',
  token: 'token',
  role: 'role',
  attributes: 'attributes',
  count: 'count',
};

关于koa2 参数传不进去

试着用了koa的框架集成进来 做一个参数验证的中间件 试了几次 发现静态的数据传过去没有问题
但是通过路由传来的数据貌似不起作用
随后发现源代码中 validate的这个方法检查属性用的是hasownproperty 这个方法 不能检查对象原型链中的属性
于是将hasownproperty 换成了 key in obj 才可以使用

var has = key in obj

希望增加未知字段过滤,或存在未知字段时报错的选项。

过滤未知字段是一个很常用且有用的功能啊,前端传参时不一定针对每个接口都pick。如果需要更严格的时候, 存在未知字段就返回错误。这样经过校验的参数都可以放心使用。不然参数经过校验后,还需要去判断存不存在一些未知字段?

I feel there is something wrong with this line of code in function checkArray()

I feel there is something wrong with this line of code in function checkArray()
....
const subRule = rule.itemType === 'object'
? rule
: rule.rule || formatRule(rule.itemType);
.....
========should be changed to:============
const subRule = rule.itemType === 'object'
? rule.rule
: rule.rule || formatRule(rule.itemType);

i can't check numeric enum

when i check numeric types,like {price:'number'},the module convert the value of the price to number.And then,check.
The problem is checking numeric enum,like {type: 'enum', values: [1, 2]}.It seems that converting is
ineffective.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.