New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@adonisjs/validator

Package Overview
Dependencies
Maintainers
2
Versions
82
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@adonisjs/validator - npm Package Compare versions

Comparing version 6.1.1 to 6.2.0

build/providers/ValidatorProvider.d.ts

2

build/adonis-typings/index.d.ts

@@ -0,2 +1,2 @@

/// <reference path="request.d.ts" />
/// <reference path="validator.d.ts" />
/// <reference path="request.d.ts" />

@@ -0,2 +1,10 @@

/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/// <reference path="./request.ts" />
/// <reference path="./validator.ts" />
/// <reference path="./request.ts" />

@@ -1,19 +0,10 @@

/// <reference path="validator.d.ts" />
declare module '@ioc:Adonis/Core/Request' {
import { SchemaContract, MessagesContract, TypedSchemaContract, ValidatorConfigContract } from '@ioc:Adonis/Core/Validator';
/**
* Adding `validate` and `validateUsing` custom methods
*/
import { ValidateFn } from '@ioc:Adonis/Core/Validator';
interface RequestContract {
/**
* Validate the current request body and query params against
* a pre-defined schema
* Validate current request data using a pre-compiled
* schema
*/
validate<T extends TypedSchemaContract | SchemaContract>(schema: T, messages?: MessagesContract, config?: Partial<ValidatorConfigContract>): Promise<T extends SchemaContract ? Promise<any> : Promise<T['props']>>;
/**
* Validate the current request body and query params against
* a pre-defined schema and collect all errors
*/
validateAll<T extends TypedSchemaContract | SchemaContract>(schema: T, messages?: MessagesContract, config?: Partial<ValidatorConfigContract>): Promise<T extends SchemaContract ? Promise<any> : Promise<T['props']>>;
validate: ValidateFn;
}
}
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/// <reference path="./validator.ts" />
declare module '@ioc:Adonis/Core/Validator' {
import { ValidatorConfig } from 'indicative/src/Contracts';
import { VanillaFormatter, JsonApiFormatter } from 'indicative-formatters';
import { ValidationDefination, ErrorFormatterContract } from 'indicative-compiler';
import { Schema, Messages, ParsedTypedSchema, TypedSchema } from 'indicative-parser';
import { schema, ValidationRulesContract as BaseRulesContract } from 'indicative/validator';
import { DateTime } from 'luxon';
import { MultipartFileContract, FileValidationOptions } from '@ioc:Adonis/Core/BodyParser';
export type Rule = {
name: string;
options?: any;
};
/**
* Error formatter interface to create custom formatters.
* The shape of rule after it has been passed
*/
export interface ValidatorFormatterContract extends ErrorFormatterContract {
export type ParsedRule<Options extends any = any> = {
name: string;
async: boolean;
allowUndefineds: boolean;
compiledOptions: Options;
};
/**
* Shape of schema core literal type
*/
export type SchemaLiteral = {
type: 'literal';
subtype: string;
rules: ParsedRule[];
};
/**
* Shape of schema core object type
*/
export type SchemaObject = {
type: 'object';
rules: ParsedRule[];
children: ParsedSchemaTree;
};
/**
* Shape of schema core array type
*/
export type SchemaArray = {
type: 'array';
rules: ParsedRule[];
each?: SchemaLiteral | SchemaObject | SchemaArray;
};
/**
* Shape of parsed schema tree. This is not extensible. All newly
* added rules will be of type literal.
*/
export type ParsedSchemaTree = {
[key: string]: SchemaLiteral | SchemaObject | SchemaArray;
};
/**
* The runtime values passed to a validation runtime
*/
export type ValidationRuntimeOptions = {
root: any;
tip: any;
pointer: string;
arrayExpressionPointer?: string;
errorReporter: ErrorReporterContract;
mutate: ((newValue: any) => void);
};
/**
* Compiler internal representation of a field to produce
* the compiled output
*/
export type ValidationField = {
name: string;
type: 'literal' | 'identifier';
};
/**
* Shape of an async validation function
*/
export type AsyncValidation<T extends any = undefined> = {
compile(type: 'array' | 'object' | 'literal', subtype: string, options?: any): ParsedRule<T>;
validate(value: any, compiledOptions: any, runtimeOptions: ValidationRuntimeOptions): Promise<void>;
};
/**
* Shape of an sync validation function
*/
export type SyncValidation<T extends any = undefined> = {
compile(type: 'array' | 'object' | 'literal', subtype: string, options?: any): ParsedRule<T>;
validate(value: any, compiledOptions: T, runtimeOptions: ValidationRuntimeOptions): void;
};
/**
* The interface that every error reporter must adhere
* to.
*/
export interface ErrorReporterContract<Messages extends any = any> {
hasErrors: boolean;
report(pointer: string, rule: string, message?: string, arrayExpressionPointer?: string, args?: any): void;
toError(): any;
toJSON(): Messages;
}
/**
* Validation rules interface that must be extended whenever
* a new rule is added using extend
* The reporter constructor contract
*/
export interface ValidationsContract extends BaseRulesContract {
export interface ErrorReporterConstructorContract<Messages extends any = any> {
new (userMessages: {
[key: string]: string;
}, bail: boolean): ErrorReporterContract<Messages>;
}
/**
* Shape of validator config.
* The contract every validation must adhere to
*/
export type ValidatorConfigContract = ValidatorConfig;
export type ValidationContract<T> = AsyncValidation<T> | SyncValidation<T>;
/**
* Copy of schema
* The compiler output function
*/
export type SchemaContract = Schema;
export interface CompilerOutput<T extends any> {
(data: any, validations: {
[rule: string]: ValidationContract<any>;
}, errorReporter: ErrorReporterContract, helpers: {
exists: ((value: any) => boolean);
isObject: ((value: any) => boolean);
}): Promise<T>;
}
/**
* Shape of typed schema
* Typed schema is a key-value pair of the `field` and a schema
* function that returns `getTree` method and optional `type`
* for it
*/
export type TypedSchemaContract = ParsedTypedSchema<TypedSchema>;
export type TypedSchema = {
[field: string]: {
t?: any;
getTree(): SchemaLiteral | SchemaObject | SchemaArray;
};
};
/**
* Copy of messages
* Signature to define a string or optional string type
*/
export type MessagesContract = Messages;
export interface StringType {
(rules?: Rule[]): {
t: string;
getTree(): SchemaLiteral;
};
optional(rules?: Rule[]): {
t?: string;
getTree(): SchemaLiteral;
};
}
/**
* Copy of validation definition
* Signature to define a date or an optional date type
*/
export type ValidationDefinitionContract = ValidationDefination;
export interface DateType {
(options?: {
format: string;
}, rules?: Rule[]): {
t: DateTime;
getTree(): SchemaLiteral;
};
optional(options?: {
format: string;
}, rules?: Rule[]): {
t?: DateTime;
getTree(): SchemaLiteral;
};
}
/**
* Validate and stop on first error
* Signature to define a boolean or optional boolean type
*/
export function validate<T extends TypedSchemaContract | SchemaContract>(data: any, validationSchema: T, messages?: MessagesContract, config?: Partial<ValidatorConfigContract>): Promise<T extends SchemaContract ? Promise<any> : Promise<T['props']>>;
export interface BooleanType {
(rules?: Rule[]): {
t: boolean;
getTree(): SchemaLiteral;
};
optional(rules?: Rule[]): {
t?: boolean;
getTree(): SchemaLiteral;
};
}
/**
* Validate all
* Signature to define a number or optional number type
*/
export function validateAll<T extends TypedSchemaContract | SchemaContract>(data: any, validationSchema: T, messages?: MessagesContract, config?: Partial<ValidatorConfigContract>): Promise<T extends SchemaContract ? Promise<any> : Promise<T['props']>>;
export interface NumberType {
(rules?: Rule[]): {
t: number;
getTree(): SchemaLiteral;
};
optional(rules?: Rule[]): {
t?: number;
getTree(): SchemaLiteral;
};
}
/**
* Extend validator by adding new validation rules. Newly added
* rule make their way back to indicative validations.
* Signature to define an object with members or an optional object
* with members.
*/
export const extend: (name: string, defination: ValidationDefinitionContract) => void;
export interface ObjectType {
(rules?: Rule[]): {
members<T extends TypedSchema>(schema: T): {
t: {
[P in keyof T]: T[P]['t'];
};
getTree(): SchemaObject;
};
};
optional(rules?: Rule[]): {
members<T extends TypedSchema>(schema: T): {
t?: {
[P in keyof T]: T[P]['t'];
};
getTree(): SchemaObject;
};
};
}
/**
* A copy of validations to be used as rules
* Signature to define an array with members or an optional array
* with members or array/optional array with optional members
*/
export const validations: ValidationsContract;
export interface ArrayType {
(rules?: Rule[]): {
members<T extends {
t?: any;
getTree(): SchemaLiteral | SchemaObject | SchemaArray;
}>(schema: T): {
t: T['t'][];
getTree(): SchemaArray;
};
anyMembers(): {
t: any[];
getTree(): SchemaArray;
};
};
optional(rules?: Rule[]): {
members<T extends {
t?: any;
getTree(): SchemaLiteral | SchemaObject | SchemaArray;
}>(schema: T): {
t?: T['t'][];
getTree(): SchemaArray;
};
anyMembers(): {
t?: any[];
getTree(): SchemaArray;
};
};
}
/**
* Collection of default formatters
* Signature to define an enum type
*/
export const formatters: {
vanilla: typeof VanillaFormatter;
jsonapi: typeof JsonApiFormatter;
export interface EnumType {
<Options extends any>(options: readonly Options[], rules?: Rule[]): {
t: Options;
getTree(): SchemaLiteral;
};
optional<Options extends any>(options: readonly Options[], rules?: Rule[]): {
t?: Options;
getTree(): SchemaLiteral;
};
}
/**
* Signature to define an enum set type
*/
export interface EnumSetType {
<Options extends any>(options: readonly Options[], rules?: Rule[]): {
t: Options[];
getTree(): SchemaLiteral;
};
optional<Options extends any>(options: readonly Options[], rules?: Rule[]): {
t?: Options[];
getTree(): SchemaLiteral;
};
}
/**
* Type for validating multipart files
*/
export interface FileType {
(options?: Partial<FileValidationOptions>, rules?: Rule[]): {
t: MultipartFileContract;
getTree(): SchemaLiteral;
};
optional(options?: Partial<FileValidationOptions>, rules?: Rule[]): {
t?: MultipartFileContract;
getTree(): SchemaLiteral;
};
}
/**
* Shape of `schema.create` output
*/
export type ParsedTypedSchema<T extends TypedSchema> = {
props: {
[P in keyof T]: T[P]['t'];
};
tree: ParsedSchemaTree;
};
export { schema };
/**
* List of schema methods available to define a schema
*/
export interface Schema {
string: StringType;
boolean: BooleanType;
number: NumberType;
date: DateType;
enum: EnumType;
enumSet: EnumSetType;
object: ObjectType;
array: ArrayType;
file: FileType;
create<T extends TypedSchema>(schema: T): ParsedTypedSchema<T>;
}
/**
* Shape of validator config
*/
export type ValidatorConfig = {
bail: boolean;
reporter: ErrorReporterConstructorContract;
};
/**
* Compile and validate function signature
*/
export interface CompileAndValidateFn {
<T extends ParsedTypedSchema<TypedSchema>>(schema: T, data: any, messages?: {
[key: string]: string;
}, options?: {
cacheKey?: string;
reporter?: ErrorReporterConstructorContract;
bail?: boolean;
}): Promise<T['props']>;
}
/**
* Compile function signature
*/
export interface CompileFn {
<T extends ParsedTypedSchema<TypedSchema>>(schema: T): CompilerOutput<T['props']>;
}
/**
* Shape of the function that validates the compiler output
*/
export interface ValidateFn {
<Fn extends (...args: any) => any>(compiledFn: Fn, data: any, messages?: {
[key: string]: string;
}, options?: {
reporter?: ErrorReporterConstructorContract;
bail?: boolean;
}): ReturnType<Fn>;
}
/**
* Shape of validator module
*/
const validator: {
/**
* Validate is a shorthand to compile + exec. If cache
* key is defined, then it will also cache the
* schemas.
*/
validate: ValidateFn;
/**
* Compile schema to an executable function
*/
compile: CompileFn;
/**
* Compile schema to an executable function
*/
compileAndValidate: CompileAndValidateFn;
/**
* Add a new validation rule
*/
addRule(name: string, ruleDefinition: ValidationContract<any>): void;
/**
* Type definition is set to any, since one can pass in a function or
* an object that has chainable API. So there is no simple way
* to guard the type definition. However, the `schema.create`
* method will fail if the final outcome doesn't have `getTree`
* method on it.
*/
addType(name: string, typeDefinition: any): void;
};
/**
* List of available validation rules. The rules are not the validation
* implementations, but instead a pointer to the validation implementation
* by it's name.
*
* Do not add primitives here, since they are covered by the types. For example
* schema.string will add rules.string automatically.
*/
export interface Rules {
/**
* Field under validation must always exists
*/
required(): Rule;
/**
* Field under validation must always exists if the
* target field exists
*/
requiredIfExists(field: string): Rule;
/**
* Field under validation must always exists, if all of the
* target field exists
*/
requiredIfExistsAll(field: string[]): Rule;
/**
* Field under validation must always exists, if any of the
* target fields exists
*/
requiredIfExistsAny(field: string[]): Rule;
/**
* Field under validation must always exists, if target field
* does not exists
*/
requiredIfNotExists(field: string): Rule;
/**
* Field under validation must always exists, if all of the
* target fields does not exists
*/
requiredIfNotExistsAll(field: string[]): Rule;
/**
* Field under validation must always exists, if any of the
* target fields does not exists
*/
requiredIfNotExistsAny(field: string[]): Rule;
/**
* Field under validation must always exists, when the defined
* expecations are met
*/
requiredWhen(field: string, operator: 'in' | 'notIn', comparisonValues: any[]): Rule;
requiredWhen(field: string, operator: '>' | '<' | '>=' | '<=', comparisonValues: number): Rule;
requiredWhen(field: string, operator: 'in' | 'notIn' | '=' | '!=' | '>' | '<' | '>=' | '<=', comparisonValues: any): Rule;
/**
* Number must be unsigned
*/
unsigned(): Rule;
/**
* String must be alpha
*/
alpha(): Rule;
/**
* String or array must have defined maximum length
*/
maxLength(length: number): Rule;
}
/**
* Shape of schema module
*/
const schema: Schema;
/**
* Shape of rules module
*/
const rules: Rules;
export { schema, rules, validator };
}

@@ -1,8 +0,7 @@

/// <reference path="../../adonis-typings/index.d.ts" />
import { validateAll, validate } from '@ioc:Adonis/Core/Validator';
import { RequestConstructorContract } from '@ioc:Adonis/Core/Request';
import { validator } from '@ioc:Adonis/Core/Validator';
/**
* Extends the request class by adding custom `validate` and
* `validateUsing` methods
* Extends the request class by adding `validate` method
* to it
*/
export default function extendRequest(Request: RequestConstructorContract, validateFn: typeof validate, validateAllFn: typeof validateAll): void;
export default function extendRequest(Request: RequestConstructorContract, validate: typeof validator['validate']): void;
"use strict";
/*
* @adonisjs/validator
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* @adonisjs/ace
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Extends the request class by adding custom `validate` and
* `validateUsing` methods
* Extends the request class by adding `validate` method
* to it
*/
function extendRequest(Request, validateFn, validateAllFn) {
/**
* Adding `validate` macro to validate the current request
* data
*/
Request.macro('validate', function requestValidate(schema, messages, config) {
return validateFn(this.all(), schema, messages, config);
function extendRequest(Request, validate) {
Request.macro('validate', function validateRequest(schema, messages, config) {
return validate(schema, {
...this.all(),
...this.allFiles(),
}, messages, config);
});
/**
* Adding `validate` macro to validate using custom data. This is shortcut
* import validator manually
*/
Request.macro('validateAll', function requestValidateAll(schema, messages, config) {
return validateAllFn(this.all(), schema, messages, config);
});
}
exports.default = extendRequest;

@@ -1,40 +0,13 @@

/// <reference path="../../adonis-typings/index.d.ts" />
import { JsonApiFormatter, VanillaFormatter } from 'indicative-formatters';
import { schema } from 'indicative/validator';
import { ValidatorConfigContract, ValidationDefinitionContract } from '@ioc:Adonis/Core/Validator';
/// <reference path="../../adonis-typings/validator.d.ts" />
import { CompileFn, ValidateFn, ValidationContract, CompileAndValidateFn } from '@ioc:Adonis/Core/Validator';
/**
* Exposes the API to validate data using the schema object.
* Module available methods/properties
*/
export declare class Validator {
config: Partial<ValidatorConfigContract>;
constructor(config: Partial<ValidatorConfigContract>);
/**
* Extend validations by adding a new rule
*/
extend(name: string, definition: ValidationDefinitionContract): void;
/**
* A copy of validations to use in favor of string
* based rules
*/
validations: import("indicative/validator").ValidationRulesContract;
/**
* Collection of default formatters
*/
formatters: {
vanilla: typeof VanillaFormatter;
jsonapi: typeof JsonApiFormatter;
};
/**
* Identifier to create declarative schema
*/
schema: typeof schema;
/**
* Validate data against the pre-defined schema and messages
*/
validate: any;
/**
* Validate data against the pre-defined schema and messages using
* validate all.
*/
validateAll: any;
}
export declare const validator: {
compile: CompileFn;
validate: ValidateFn;
compileAndValidate: CompileAndValidateFn;
rules: import("@ioc:Adonis/Core/Validator").Rules;
addRule: (name: string, ruleDefinition: ValidationContract<any>) => void;
addType: (name: string, typeDefinition: any) => void;
};

@@ -10,74 +10,94 @@ "use strict";

*/
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/// <reference path="../../adonis-typings/index.ts" />
const indicative_formatters_1 = require("indicative-formatters");
const validator_1 = require("indicative/validator");
const ValidationException_1 = require("../Exceptions/ValidationException");
const Schema_1 = require("../Schema");
const Compiler_1 = require("../Compiler");
const Rules_1 = require("../Rules");
const helpers_1 = require("./helpers");
const validations = __importStar(require("../Validations"));
const ErrorReporter_1 = require("../ErrorReporter");
/**
* Exposes the API to validate data using the schema object.
* The compiled output runtime helpers
*/
class Validator {
constructor(config) {
this.config = config;
/**
* A copy of validations to use in favor of string
* based rules
*/
this.validations = validator_1.validations;
/**
* Collection of default formatters
*/
this.formatters = {
vanilla: indicative_formatters_1.VanillaFormatter,
jsonapi: indicative_formatters_1.JsonApiFormatter,
};
/**
* Identifier to create declarative schema
*/
this.schema = validator_1.schema;
/**
* Validate data against the pre-defined schema and messages
*/
this.validate = async function (data, validationSchema, messages, config) {
try {
config = Object.assign({}, this.config, config);
const validated = await validator_1.validate(data, validationSchema, messages, config);
return validated;
}
catch (error) {
if (Array.isArray(error)) {
throw new ValidationException_1.ValidationException(error);
}
else {
throw error;
}
}
}.bind(this);
/**
* Validate data against the pre-defined schema and messages using
* validate all.
*/
this.validateAll = async function (data, validationSchema, messages, config) {
try {
config = Object.assign({}, this.config, config);
const validated = await validator_1.validateAll(data, validationSchema, messages, config);
return validated;
}
catch (error) {
if (Array.isArray(error)) {
throw new ValidationException_1.ValidationException(error);
}
else {
throw error;
}
}
}.bind(this);
const HELPERS = { exists: helpers_1.existy, isObject: helpers_1.isObject };
/**
* Cache to store the compiled schemas
*/
const COMPILED_CACHE = {};
/**
* An object of messages to use as fallback, when no custom
* messages are defined.
*/
const NOOP_MESSAGES = {};
/**
* Compiles the schema to an executable function
*/
const compile = (parsedSchema) => new Compiler_1.Compiler(parsedSchema.tree).compile();
/**
* Execute the compiled schema function with runtime data and custom messages.
* We allow custom messages and error reporter per call, so that you don't
* have to re-compile the schema when trying to use different set of
* validation messages.
*/
const validate = (compiledFn, data, messages, options) => {
let Reporter = ErrorReporter_1.VanillaErrorReporter;
let bail = false;
if (options) {
if (options.reporter) {
Reporter = options.reporter;
}
if (options.bail !== undefined) {
bail = options.bail;
}
}
return compiledFn(data, validations, new Reporter(messages || NOOP_MESSAGES, bail), HELPERS);
};
/**
* Validate data using pre-parsed schema. The schema will be compiled and
* cached using the cache key (if defined).
*/
const compileAndValidate = (parsedSchema, data, messages, options) => {
if (!options || !options.cacheKey) {
return validate(compile(parsedSchema), data, messages, options);
}
let compiledFn = COMPILED_CACHE[options.cacheKey];
if (!compiledFn) {
compiledFn = compile(parsedSchema);
COMPILED_CACHE[options.cacheKey] = compiledFn;
}
return validate(compiledFn, data, messages, options);
};
/**
* Extend validator by adding a new rule
*/
const addRule = function (name, ruleDefinition) {
/**
* Extend validations by adding a new rule
* Adding to the rules object, so that one can reference the method. Also
* interface of rules list has to be extended seperately.
*/
extend(name, definition) {
validator_1.extend(name, definition);
}
}
exports.Validator = Validator;
Rules_1.rules[name] = Rules_1.getRuleFn(name);
validations[name] = ruleDefinition;
};
/**
* Add a new type
*/
const addType = function (name, typeDefinition) {
Schema_1.schema[name] = typeDefinition;
};
/**
* Module available methods/properties
*/
exports.validator = {
compile,
validate,
compileAndValidate,
rules: Rules_1.rules,
addRule,
addType,
};
# The MIT License
Copyright 2019 Harminder virk, contributors
Copyright 2020 Harminder virk, contributors

@@ -5,0 +5,0 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

{
"name": "@adonisjs/validator",
"version": "6.1.1",
"version": "6.2.0",
"description": "Validator for adonis framework",
"main": "./build/providers/ValidationProvider.js",
"main": "build/providers/ValidatorProvider.js",
"files": [
"build/adonis-typings",
"build/providers",
"build/templates",
"build/src"

@@ -16,11 +15,12 @@ ],

"test": "node japaFile.js",
"lint": "eslint . --ext .ts",
"clean": "del build",
"compile": "npm run lint && npm run clean && tsc",
"copy:files": "copyfiles \"templates/**/*.txt\" build",
"build": "npm run compile && npm run copy:files",
"build": "npm run compile",
"prepublishOnly": "npm run build",
"commit": "git-cz",
"release": "np",
"version": "npm run build"
"version": "npm run build",
"lint": "eslint . --ext=.ts",
"benchmarks": "node build/benchmarks/index.js"
},

@@ -44,25 +44,2 @@ "types": "./build/adonis-typings/index.d.ts",

"homepage": "https://github.com/adonisjs/adonis-validation-provider#readme",
"devDependencies": {
"@adonisjs/encryption": "^1.0.3",
"@adonisjs/fold": "^6.2.3",
"@adonisjs/http-server": "^1.6.0",
"@adonisjs/logger": "^1.1.7",
"@adonisjs/mrm-preset": "^2.2.3",
"@adonisjs/profiler": "^1.2.4",
"@adonisjs/session": "^2.1.0",
"@types/node": "^13.1.0",
"commitizen": "^4.0.3",
"copyfiles": "^2.1.1",
"cz-conventional-changelog": "^3.0.2",
"del-cli": "^3.0.0",
"doctoc": "^1.4.0",
"eslint": "^6.8.0",
"eslint-plugin-adonis": "^1.0.4",
"husky": "^3.1.0",
"japa": "^3.0.1",
"mrm": "^2.0.2",
"np": "^5.2.1",
"ts-node": "^8.5.4",
"typescript": "^3.7.4"
},
"nyc": {

@@ -91,18 +68,43 @@ "exclude": [

},
"dependencies": {
"@poppinss/utils": "^2.1.1",
"indicative": "^7.4.4"
},
"peerDependencies": {
"@adonisjs/fold": "^6.0.0"
},
"adonisjs": {
"templates": {
"config": "validator.txt"
}
},
"publishConfig": {
"access": "public",
"tag": "alpha"
},
"devDependencies": {
"@adonisjs/bodyparser": "^3.2.2",
"@adonisjs/encryption": "^1.0.4",
"@adonisjs/fold": "^6.3.3",
"@adonisjs/http-server": "^1.7.1",
"@adonisjs/logger": "^1.1.8",
"@adonisjs/mrm-preset": "^2.2.4",
"@adonisjs/profiler": "^2.0.0",
"@hapi/joi": "^17.1.0",
"@types/node": "^13.7.0",
"benchmark": "^2.1.4",
"class-validator": "^0.11.0",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.1.0",
"dedent": "^0.7.0",
"del-cli": "^3.0.0",
"doctoc": "^1.4.0",
"endent": "^1.4.0",
"eslint": "^6.8.0",
"eslint-plugin-adonis": "^1.0.6",
"execa": "^4.0.0",
"husky": "^4.2.1",
"indicative": "^7.4.4",
"indicative-compiler": "^7.2.4",
"japa": "^3.0.1",
"kleur": "^3.0.3",
"matcha": "^0.7.0",
"mrm": "^2.0.4",
"np": "^5.2.1",
"ts-node": "^8.6.2",
"typescript": "^3.7.5"
},
"dependencies": {
"@types/luxon": "^1.21.0",
"lodash.get": "^4.4.2",
"luxon": "^1.22.0"
}
}

@@ -0,1 +1,10 @@

<div align="center"><img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1564392111/adonis-banner_o9lunk.png" width="600px"></div>
# AdonisJS Validator
> Schema validator for AdonisJS
[![circleci-image]][circleci-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url]
I have been maintaining [indicative](https://indicative.adonisjs.com/) (used by this repo) for many years and learned a lot about the validation engines. This time I want to approach data validation from scratch and address lot of design issues that Indicative has and also squeeze out maximum performance this time.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->

@@ -5,60 +14,65 @@ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Data Validator For AdonisJS](#data-validator-for-adonisjs)
- [
Website
|
Guides
|
Contributing
](#website%0A----%0A------%0A----%0A------guides%0A----%0A------%0A----%0A------contributing)
- [Benchmarks](#benchmarks)
- [Goals](#goals)
- [Usage](#usage)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
<div align="center">
<img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1558612869/adonis-readme_zscycu.jpg" width="600px">
</div>
## Benchmarks
Let's compare the validator performance in comparison to some of the famous libraries in the Node.js Ecosystem.
<br />
- [Joi](https://hapi.dev/family/joi/) is one of the most famous and widely used schema validator for Node.js.
- [Class Validator](https://github.com/typestack/class-validator) is a popular library in the Typescript world, since it allows you to keep your static types in sync with the runtime validations.
- [Indicative](https://indicative.adonisjs.com/) My own work.
<div align="center">
<h3>Data Validator For AdonisJS</h3>
<p>
AdonisJS validator uses <a href="https://indicative.adonisjs.com">indicative</a> to validate the request data provides complete type information for validated data.
</p>
</div>
![](./benchmarks.png)
<br />
<details>
<summary><strong> Textual Version </strong></summary>
<pre>
<code>
Benchmarking against flat object
AdonisJS x 6,777,738 ops/sec ±0.53% (81 runs sampled)
Joi x 705,094 ops/sec ±0.62% (81 runs sampled)
Indicative x 855,792 ops/sec ±0.30% (84 runs sampled)
Class Validator x 372,847 ops/sec ±0.38% (84 runs sampled)
Fastest is AdonisJS
<div align="center">
Benchmarking against flat object with extra properties
AdonisJS x 6,685,496 ops/sec ±0.41% (81 runs sampled)
Joi x 445,545 ops/sec ±0.45% (83 runs sampled)
Indicative x 836,625 ops/sec ±0.44% (84 runs sampled)
Fastest is AdonisJS
[![circleci-image]][circleci-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url]
Benchmarking against nested object
AdonisJS x 4,742,486 ops/sec ±0.52% (82 runs sampled)
Joi x 395,813 ops/sec ±0.48% (84 runs sampled)
Indicative x 532,652 ops/sec ±0.27% (85 runs sampled)
Class Validator x 216,392 ops/sec ±0.82% (83 runs sampled)
Fastest is AdonisJS
</div>
Benchmarking against array of objects
AdonisJS x 2,330,326 ops/sec ±0.42% (82 runs sampled)
Joi x 297,187 ops/sec ±0.47% (82 runs sampled)
Indicative x 394,948 ops/sec ±0.30% (83 runs sampled)
Class Validator x 192,939 ops/sec ±1.25% (82 runs sampled)
Fastest is AdonisJS
</code>
</pre>
</details>
<div align="center">
<h3>
<a href="https://adonisjs.com">
Website
</a>
<span> | </span>
<a href="https://adonisjs.com/docs/validator">
Guides
</a>
<span> | </span>
<a href="CONTRIBUTING.md">
Contributing
</a>
</h3>
</div>
## Goals
**No code is the fastest code**. In other words, making something fast is not a big deal, if you cut out all the features and compromise usability on every front.
<div align="center">
<sub>Built with ❤︎ by <a href="https://github.com/thetutlage">Harminder Virk</a>
</div>
I didn't started with making one of the fastest validation engines for Node.js. The goals were completely different and performance was just one of them.
- [x] **Treat Typescript as a first class citizen**. Runtime validations and static types should always be in sync. In other words, no need to write seperate interfaces for maintaining types.
- [x] **Performance is important**. Validating user input is a very common task every Web server has to perform and hence squeezing out more performance on this front is critical.
- [x] **Do not mutate original data**: The validator returns a new copy of data, holding only the validated properties. In the process, the original data object is never mutated.
- [x] **Don't be stringent about errors format**: Many validation libraries returns errors in a single hardcoded structure. If you need them in a different shape, then running a loop on the errors is the only option.
With AdonisJS, it is as simple as creating an Error Formatter with couple of methods on it.
## Usage
Docs will be added soon to the AdonisJS official website
[circleci-image]: https://img.shields.io/circleci/project/github/adonisjs/adonis-validation-provider/master.svg?style=for-the-badge&logo=circleci

@@ -65,0 +79,0 @@ [circleci-url]: https://circleci.com/gh/adonisjs/adonis-validation-provider "circleci"

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