Javascript Node.js 的验证库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4088723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:33:24  来源:igfitidea点击:

Validation library for Node.js

javascriptvalidationnode.js

提问by ajsie

Is there a good validation framework for node.js that validates a variable for:

是否有一个很好的 node.js 验证框架来验证变量:

  • if its a type of String, Date, Number etc
  • max and min length
  • email, phone
  • etc...
  • 如果它是字符串、日期、数字等类型
  • 最大和最小长度
  • 电子邮件、电话
  • 等等...

回答by Baggz

I recently discovered node-validatorby chriso.

我最近发现了chriso 的节点验证器

Example

例子

var check = require('validator').check,
    sanitize = require('validator').sanitize

//Validate
check('[email protected]').len(6, 64).isEmail();       //Methods are chainable
check('abc').isInt();                               //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt();      //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);

//Sanitize / Filter
var int = sanitize('0123').toInt();                  //123
var bool = sanitize('true').toBoolean();             //true
var str = sanitize(' \s\t\r hello \n').trim();      //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a');        //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('&lt;a&gt;').entityDecode();     //'<a>'

回答by Parris

I wanted ruby on rails and cakephp style validations. I knew it was something I would use over and over so I made this quick npm module: https://npmjs.org/package/iz

我想要 ruby​​ on rails 和 cakephp 样式验证。我知道这是我会反复使用的东西,所以我制作了这个快速的 npm 模块:https://npmjs.org/package/iz

It reads semantically like well like jasmine, and can be used client or server side. This means it comes with support for commonjs and amd along with validation rules passed in via JSON.

它在语义上像 jasmine 一样好读,并且可以在客户端或服务器端使用。这意味着它支持 commonjs 和 amd 以及通过 JSON 传入的验证规则。

It is pretty well unit tested, it has no production dependencies, and the scope is locked down to just validation. We seem to have a small community going now. Ideas, feedback and pull requests are all welcome.

它经过了很好的单元测试,没有生产依赖性,并且范围仅限于验证。我们现在似乎有一个小社区。欢迎提出想法、反馈和请求请求。

Current library functions:

当前库函数:

iz.alphaNumeric(*);               // Is number or string(contains only numbers or strings)
iz.between(number, start, end);   // Number is start or greater but less than or equal to end, all params numeric
iz.blank(*);                      // Empty string, undefined or null
iz.boolean(*);                    // true, false, 0, 1
iz.cc(*);                         // Luhn checksum approved value
iz.date(*);                       // Is a data obj or is a string that is easily converted to a date
iz.decimal(*);                    // Contains 1 decimal point and potentially can have a - at the beginning
iz.email(*);                      // Seems like a valid email address
iz.extension(ob1, ob2);           // If obj2's methods are all found in obj1
iz.fileExtension(arr, value);     // Checks if the extension of value is in arr. An obj can be provide, but must have indexOf defined.
iz.fileExtensionAudio(value);     // Check against mp3, ogg, wav, aac
iz.fileExtensionImage(value);     // Check against png, jpg, jpeg, gif, bmp, svg, gif
iz.inArray(arr, value);           // If * is in the array
iz.int(*, bool (optional));       // Is an int. If the 2nd variable is true (false by default) a decimal is allowed
iz.ip(str);                       // str resembles an IPV4 or IPV6 address
iz.minLen(val, min);              // val (str or arr) is greater than min
iz.maxLen(val, max);              // val (str or arr) is shorter than max
iz.multiple(num, mult);           // Number is multiple of another number
iz.number(*);                     // Is either an int or decimal
iz.ofType(obj, typeName);         // If it is a named object, and the name matches the string
iz.phone(str, canHaveExtension?); // Is an american phone number. Any punctuations are allowed.
iz.postal(*);                     // Is a postal code or zip code
iz.ssn(*);                        // Is a social security number

回答by Trantor Liu

Node-validatoris a library of string validation, filtering and sanitization methods.

Node-validator是一个字符串验证、过滤和清理方法库。

So if you want to have better support for Numbers and Arrays, you may try Chai.js. Here's some examples:

所以如果你想更好地支持数字和数组,你可以试试Chai.js。下面是一些例子:

var expect = require('chai').expect;
try {
    expect([1, 2, 3]).to.have.length.below(4);
    expect(5).to.be.within(3,6);
    expect('test').to.have.length(4);
} catch (e) {
    // should not occur
}

回答by intuited

I gather that this is the sort of thing that the schemamodule is meant to do. Note that it is labeled as being "in development" (tagged as v0.1a). I haven't tried it myself, but it looks pretty good from the examples shown in the README.

我认为这是模式模块要做的事情。请注意,它被标记为“正在开发”(标记为 v0.1a)。我自己没有尝试过,但从 README 中显示的示例来看,它看起来不错。

回答by Tor Valamo

Not on a variable level, but on a function argument level:

不是在变量级别,而是在函数参数级别:

http://github.com/torvalamo/argtype.js

http://github.com/torvalamo/argtype.js

Date currently needs to pass as type 'object'. It is definately something that I have forgotten, and will put on the todo-list. ;)

日期当前需要作为“对象”类型传递。这绝对是我已经忘记的事情,并将放在待办事项列表中。;)

Specific max and min length is not supported, and will probably not be implemented (but who knows). Email, phone and all that can be checked by regex. See the example on the github page, which includes a (simple) regex example.

不支持特定的最大和最小长度,并且可能不会实现(但谁知道)。电子邮件、电话和所有可以通过正则表达式检查的内容。请参阅 github 页面上的示例,其中包含一个(简单的)正则表达式示例。

回答by Eduardo Nunes

I recommend validathere is lack of documentation however it is pretty simple to understand looking at the examples.

我建议valida有缺少文档然而这是很容易理解看的例子

Valida features are:

Valida 的特点是:

  • Sanitization
  • Synchronous and asynchronous validation
  • Groups
  • Extensible
  • 消毒
  • 同步和异步验证
  • 团体
  • 可扩展

回答by Wilker Lucio

I'm finishing writing a library on Javascript validations (both node and browser), I'll be writing the docs on the next few days, but the code is almost ready: https://github.com/wilkerlucio/composed-validations

我正在编写关于 Javascript 验证(节点和浏览器)的库,我将在接下来的几天编写文档,但代码几乎准备好了:https: //github.com/wilkerlucio/composed-validations

Please let me know if you have any questions/suggestions on it :)

如果您对此有任何问题/建议,请告诉我:)