Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fastest-validator

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fastest-validator - npm Package Compare versions

Comparing version 0.4.3 to 0.5.0

examples/custom.js

4

.vscode/launch.json

@@ -10,4 +10,4 @@ {

"request": "launch",
"name": "Launch example",
"program": "${workspaceRoot}\\examples\\simple.js"
"name": "Launch dev",
"program": "${workspaceRoot}\\examples\\custom.js"
},

@@ -14,0 +14,0 @@ {

@@ -1,4 +0,1 @@

const Benchmarkify = require("benchmarkify");
Benchmarkify.printHeader("fastest-validator benchmark");
require("./suites/" + (process.argv[2] || "simple"));
"use strict";
const Benchmarkify = require("benchmarkify");
const bench = new Benchmarkify({ async: false, name: "Email validating methods"});
const benchmark = new Benchmarkify("Fastest validator benchmark").printHeader();
let bench = benchmark.createSuite("Email validating methods");
const Validator = require("../../index");

@@ -7,0 +9,0 @@ const v = new Validator();

"use strict";
const Benchmarkify = require("benchmarkify");
const bench = new Benchmarkify({ async: false, name: "Simple object"});
const benchmark = new Benchmarkify("Fastest validator benchmark").printHeader();
let bench = benchmark.createSuite("Simple object");
const Validator = require("../../index");

@@ -40,3 +42,3 @@ const v = new Validator();

bench.add("compile & validate", () => {
bench.ref("compile & validate", () => {
let res = v.validate(obj, schema);

@@ -43,0 +45,0 @@ if (res !== true)

@@ -0,1 +1,3 @@

/* eslint-disable no-console */
"use strict";

@@ -14,4 +16,6 @@

settings: { type: "object", props: {
notify: { type: "boolean" }
//notify: { type: ["boolean", "object" ] } // 2 accepted type: Boolean or Object
notify: [
{ type: "boolean" },
{ type: "object" }
]
}},

@@ -45,3 +49,6 @@ sex: { type: "string", enum: ["male", "female"] },

settings: {
notify: true
//notify: true,
notify: {
corner: "top"
}
},

@@ -48,0 +55,0 @@ roles: [

@@ -0,1 +1,3 @@

/* eslint-disable no-console */
let Validator = require("../index");

@@ -2,0 +4,0 @@

@@ -0,1 +1,3 @@

/* eslint-disable no-console */
let Validator = require("../index");

@@ -6,5 +8,5 @@

const schema = {
id: { type: "number", positive: true, integer: true },
name: { type: "string", min: 3, max: 255 },
status: "boolean" // short-hand def
id: { type: "number", positive: true, integer: true },
name: { type: "string", min: 3, max: 255 },
status: "boolean" // short-hand def
};

@@ -25,5 +27,5 @@

field: 'name',
message: 'The \'name\' field length must be larger than or equal to3 characters long!'
message: 'The \'name\' field length must be larger than or equal to 3 characters long!'
}
]
*/

@@ -50,8 +50,10 @@ "use strict";

let rules;
// Process the whole schema
if (Array.isArray(schema)) {
if (schema.length !== 1)
throw new Error("If the schema is an Array, must be only one element!");
// Multiple schemas
if (schema.length == 0)
throw new Error("If the schema is an Array, must contain at least one element!");
rules = self._processRule(schema[0], null, false);
return this._checkWrapper(flatten(schema.map(r => this._processRule(r, null, false))), true);
} else if (schema != null && typeof schema === "object") {

@@ -82,2 +84,15 @@ rules = flatten(Object.keys(schema).map(name => self._processRule(schema[name], name, false)));

if (Array.isArray(rule)) {
// Compile the multiple schemas
checks.push({
fn: this.compile(rule),
type: "_multi",
name: name,
schema: rule,
iterate: iterate
});
return checks;
}
if (this.rules[rule.type]) {

@@ -125,4 +140,5 @@ checks.push({

* @param {Array} rules
* @param {Boolean} isMultipleRules
*/
Validator.prototype._checkWrapper = function(rules) {
Validator.prototype._checkWrapper = function(rules, isMultipleRules) {
const self = this;

@@ -167,2 +183,10 @@

let res = check.fn.call(self, value, schema, stack);
if (isMultipleRules) {
if (res === true) {
// Jump out after first success and clear previous errors
return true;
}
}
if (res !== true)

@@ -169,0 +193,0 @@ self.handleResult(errors, stack, res);

{
"name": "fastest-validator",
"version": "0.4.3",
"version": "0.5.0",
"dependencies": {
"balanced-match": {
"version": "0.4.2"
},
"brace-expansion": {
"version": "1.1.6"
},
"concat-map": {

@@ -15,6 +9,27 @@ "version": "0.0.1"

"fs.realpath": {
"version": "1.0.0"
"version": "1.0.0",
"from": "fs.realpath@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz"
},
"glob": {
"version": "7.1.1"
"version": "7.1.2",
"from": "glob@7.1.2",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz",
"dependencies": {
"balanced-match": {
"version": "1.0.0",
"from": "balanced-match@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz"
},
"brace-expansion": {
"version": "1.1.8",
"from": "brace-expansion@>=1.1.7 <2.0.0",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz"
},
"minimatch": {
"version": "3.0.4",
"from": "minimatch@>=3.0.4 <4.0.0",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz"
}
}
},

@@ -37,5 +52,2 @@ "inflight": {

},
"minimatch": {
"version": "3.0.3"
},
"once": {

@@ -42,0 +54,0 @@ "version": "1.4.0"

{
"name": "fastest-validator",
"version": "0.4.3",
"version": "0.5.0",
"description": "The fastest JS validator library for NodeJS",

@@ -8,6 +8,7 @@ "main": "index.js",

"bench": "node benchmark/index.js",
"example": "nodemon examples/index.js",
"dev": "nodemon examples/index.js",
"ci": "jest --watch",
"test": "jest --coverage",
"lint": "eslint --ext=.js src test",
"deps": "npm-check -u",
"coverall": "cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js"

@@ -32,9 +33,11 @@ },

"devDependencies": {
"benchmarkify": "^1.0.0",
"benchmarkify": "2.1.0",
"coveralls": "^2.12.0",
"eslint": "^3.17.0",
"jest": "^19.0.2"
"eslint": "4.1.1",
"jest": "20.0.4",
"jest-cli": "20.0.4",
"npm-check": "5.4.4"
},
"dependencies": {
"glob": "^7.1.1",
"glob": "7.1.2",
"lodash.defaultsdeep": "4.6.0",

@@ -41,0 +44,0 @@ "lodash.flatten": "4.4.0"

@@ -13,2 +13,3 @@ [![Build Status](https://travis-ci.org/icebob/fastest-validator.svg?branch=master)](https://travis-ci.org/icebob/fastest-validator)

* nested object & array handling
* multiple validators for fields
* customizable error messages

@@ -75,3 +76,3 @@ * programmable error object

expected: 3,
actual: 2,
actual: 2,
field: 'name',

@@ -132,2 +133,18 @@ message: 'The \'name\' field length must be larger than or equal to 3 characters long!'

# Multiple validators
There is possible to define more validators for a field. In this case if one of all validators is success, the field will be valid.
```js
let schema = {
cache: [
{ type: "string" },
{ type: "boolean" }
]
}
v.validate({ cache: true }, schema); // Valid
v.validate({ cache: "redis://" }, schema); // Valid
v.validate({ cache: 150 }, schema); // Fail
```
# Built-in validators

@@ -392,2 +409,78 @@

# Custom validator
You can also create your custom validator.
```js
let v = new Validator({
messages: {
// Register our new error message text
evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
}
});
// Register a custom 'even' validator
v.add("even", value => {
if (value % 2 != 0)
return v.makeError("evenNumber", null, value);
return true;
});
const schema = {
name: { type: "string", min: 3, max: 255 },
age: { type: "even" }
};
console.log(v.validate({ name: "John", age: 20 }, schema));
// Returns: true
console.log(v.validate({ name: "John", age: 19 }, schema));
/* Returns an array with errors:
[{
type: 'evenNumber',
expected: null,
actual: 19,
field: 'age',
message: 'The \'age\' field must be an even number! Actual: 19'
}]
*/
```
Or you can use the `custom` type with inline checker function:
```js
let v = new Validator({
messages: {
// Register our new error message text
weightMin: "The weight must be larger than {expected}! Actual: {actual}"
}
});
const schema = {
name: { type: "string", min: 3, max: 255 },
weight: {
type: "custom",
minWeight: 10,
check(value, schema) {
return (value < schema.minWeight)
? this.makeError("weightMin", schema.minWeight, value)
: true;
}
}
};
console.log(v.validate({ name: "John", weight: 50 }, schema));
// Returns: true
console.log(v.validate({ name: "John", weight: 8 }, schema));
/* Returns an array with errors:
[{
type: 'weightMin',
expected: 10,
actual: 8,
field: 'weight',
message: 'The weight must be larger than 10! Actual: 8'
}]
*/
```
# Custom error messages (l10n)

@@ -411,3 +504,3 @@ You can set your custom messages in constructor of validator.

expected: 6,
actual: 4,
actual: 4,
field: 'name',

@@ -421,43 +514,43 @@ message: 'A(z) \'name\' mező túl rövid. Minimum: 6, Jelenleg: 4'

## Message types
Name | Default text
---- | -------------
`required` | The '{field}' field is required!
`string` | The '{field}' field must be a string!
`stringEmpty` | The '{field}' field must not be empty!
`stringMin`: | The '{field}' field length must be larger than or equal to {expected} characters long!
`stringMax`: | The '{field}' field length must be less than or equal to {expected} characters long!
`stringLength` | The '{field}' field length must be {expected} characters long!
`stringPattern` | The '{field}' field fails to match the required pattern!
`stringContains` | The '{field}' field must contain the '{expected}' text!
`stringEnum` | The '{field}' field does not match any of the allowed values!
`number` | The '{field}' field must be a number!
`numberMin` | The '{field}' field must be larger than or equal to {expected}!
`numberMax` | The '{field}' field must be less than or equal to {expected}!
`numberEqual` | The '{field}' field must be equal with {expected}!
`numberNotEqual` | The '{field}' field can't be equal with {expected}!
`numberInteger` | The '{field}' field must be an integer!
`numberPositive` | The '{field}' field must be a positive number!
`numberNegative` | The '{field}' field must be a negative number!
`array` | The '{field}' field must be an array!
`arrayEmpty` | The '{field}' field must not be an empty array!
`arrayMin` | The '{field}' field must contain at least {expected} items!
`arrayMax` | The '{field}' field must contain less than or equal to {expected} items!
`arrayLength` | The '{field}' field must contain {expected} items!
`arrayContains` | The '{field}' field must contain the '{expected}' item!
`arrayEnum`: | The '{field} field value '{expected}' does not match any of the allowed values!
`boolean` | The '{field}' field must be a boolean!
`function` | The '{field}' field must be a function!
`date` | The '{field}' field must be a Date!
`dateMin` | The '{field}' field must be larger than or equal to {expected}!
`dateMax` | The '{field}' field must be less than or equal to {expected}!
`forbidden` | The '{field}' field is forbidden!
`email` | The '{field}' field must be a valid e-mail!
Name | Default text
------------------- | -------------
`required` | The '{field}' field is required!
`string` | The '{field}' field must be a string!
`stringEmpty` | The '{field}' field must not be empty!
`stringMin` | The '{field}' field length must be larger than or equal to {expected} characters long!
`stringMax` | The '{field}' field length must be less than or equal to {expected} characters long!
`stringLength` | The '{field}' field length must be {expected} characters long!
`stringPattern` | The '{field}' field fails to match the required pattern!
`stringContains` | The '{field}' field must contain the '{expected}' text!
`stringEnum` | The '{field}' field does not match any of the allowed values!
`number` | The '{field}' field must be a number!
`numberMin` | The '{field}' field must be larger than or equal to {expected}!
`numberMax` | The '{field}' field must be less than or equal to {expected}!
`numberEqual` | The '{field}' field must be equal with {expected}!
`numberNotEqual` | The '{field}' field can't be equal with {expected}!
`numberInteger` | The '{field}' field must be an integer!
`numberPositive` | The '{field}' field must be a positive number!
`numberNegative` | The '{field}' field must be a negative number!
`array` | The '{field}' field must be an array!
`arrayEmpty` | The '{field}' field must not be an empty array!
`arrayMin` | The '{field}' field must contain at least {expected} items!
`arrayMax` | The '{field}' field must contain less than or equal to {expected} items!
`arrayLength` | The '{field}' field must contain {expected} items!
`arrayContains` | The '{field}' field must contain the '{expected}' item!
`arrayEnum` | The '{field} field value '{expected}' does not match any of the allowed values!
`boolean` | The '{field}' field must be a boolean!
`function` | The '{field}' field must be a function!
`date` | The '{field}' field must be a Date!
`dateMin` | The '{field}' field must be larger than or equal to {expected}!
`dateMax` | The '{field}' field must be less than or equal to {expected}!
`forbidden` | The '{field}' field is forbidden!
`email` | The '{field}' field must be a valid e-mail!
## Message fields
Name | Description
---- | -------------
`field` | Name of field
`expected` | The expected value of field
`actual` | The actual value of field
`type` | Type of field
Name | Description
----------- | -------------
`field` | Name of field
`expected` | The expected value of field
`actual` | The actual value of field
`type` | Type of field

@@ -464,0 +557,0 @@ ## Development

@@ -15,3 +15,3 @@ "use strict";

expect(Object.keys(v.rules).length).toBe(11);
expect(Object.keys(v.rules).length).toBe(12);
});

@@ -128,6 +128,10 @@

v.compile([{ type: "array", items: "number" }]);
v.compile([
{ type: "array", items: "number" },
{ type: "string", min: 2 }
]);
expect(v._processRule).toHaveBeenCalledTimes(1);
expect(v._processRule).toHaveBeenCalledTimes(2);
expect(v._processRule).toHaveBeenCalledWith({"type": "array", items: "number"}, null, false);
expect(v._processRule).toHaveBeenCalledWith({"type": "string", min: 2 }, null, false);
});

@@ -572,20 +576,16 @@

describe("Test root-level array", () => {
describe("Test multiple rules", () => {
const v = new Validator();
let schema = [{ type: "array", items: {
type: "object", props: {
id: "number",
name: "string"
}
}}];
let schema = {
value: [
{ type: "string", min: 3, max: 255 },
{ type: "boolean" }
]
};
let check = v.compile(schema);
it("should give true if obj is valid", () => {
let obj = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "James" }
];
it("should give true if value is string", () => {
let obj = { value: "John" };

@@ -596,32 +596,39 @@ let res = check(obj);

});
it("should give true if value is boolean", () => {
let obj = { value: true };
let res = check(obj);
expect(res).toBe(true);
obj = { value: false };
res = check(obj);
expect(res).toBe(true);
});
it("should give error if an element is not object", () => {
let obj = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
123
];
it("should give error if the value is not string and not boolean", () => {
let obj = { value: 100 };
let res = check(obj);
expect(res.length).toBe(3);
expect(res[0].type).toBe("object");
expect(res[0].field).toBe("[2]");
expect(res.length).toBe(2);
expect(res[0].type).toBe("string");
expect(res[0].field).toBe("value");
expect(res[1].type).toBe("boolean");
expect(res[1].field).toBe("value");
});
it("should give error if an element is not object", () => {
let obj = [
{ id: 1, name: "John" },
{ id: 2, _name: "Jane" }
];
it("should give error if the value is a too short string", () => {
let obj = { value: "Al" };
let res = check(obj);
expect(res.length).toBe(1);
expect(res[0].type).toBe("required");
expect(res[0].field).toBe("[1].name");
expect(res.length).toBe(2);
expect(res[0].type).toBe("stringMin");
expect(res[0].field).toBe("value");
expect(res[1].type).toBe("boolean");
expect(res[1].field).toBe("value");
});
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc