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

@aomex/validator

Package Overview
Dependencies
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aomex/validator - npm Package Compare versions

Comparing version 0.0.12 to 0.0.13

14

CHANGELOG.md
# @aomex/validator
## 0.0.13
### Patch Changes
- [`9881653`](https://github.com/aomex/aomex/commit/988165361439738d27bc29bd0ed5a85c608db5ef) Thanks [@geekact](https://github.com/geekact)! - feat(validator)!: create namespace for each validator
- [`ab18463`](https://github.com/aomex/aomex/commit/ab1846384f784aeb63d50f6be7778802117c94d5) Thanks [@geekact](https://github.com/geekact)! - feat(validator): remove duplicate value for enum rule
- [`accbb60`](https://github.com/aomex/aomex/commit/accbb606beadbbb02bdcf5512a0af2fb221db608) Thanks [@geekact](https://github.com/geekact)! - feat(validator): make validators immutable
- [`62cb525`](https://github.com/aomex/aomex/commit/62cb5251d4c482fd4dc1823c3cfabaea1eeae677) Thanks [@geekact](https://github.com/geekact)! - feat(validator): support date-time
- [`15ecd1c`](https://github.com/aomex/aomex/commit/15ecd1c75bc21929f79980b32e63ea46e081cc6a) Thanks [@geekact](https://github.com/geekact)! - refactor(validator)!: declare magistrate namespace
## 0.0.12

@@ -4,0 +18,0 @@

297

dist/index.d.ts
import { OpenAPI } from '@aomex/openapi-type';
type ValidateResult<T> = ValidateResultOK<T> | ValidateResultError;
interface ValidateResultOK<T> {
ok: T;
declare namespace magistrate {
type Result<T> = Ok<T> | Fail;
interface Ok<T> {
ok: T;
}
interface Fail {
errors: {
path: string[];
message: string;
}[];
}
}
interface ValidateResultError {
errors: {
path: string[];
message: string;
}[];
}
type PartialOpenAPISchema = Pick<OpenAPI.SchemaObject, 'title' | 'description' | 'deprecated' | 'example' | 'externalDocs'>;
interface ValidatorOptions<Type> {
defaultValue?: Type | (() => Type);
required: boolean;
nullable: boolean;
transform?: (value: any) => Promise<any> | any;
docs?: PartialOpenAPISchema;
}
declare const magistrate: {
ok: <T>(result: T) => magistrate.Ok<T>;
fail: (message: string, key: string, superKeys: string[]) => magistrate.Fail;
noError: <T_1>(result: magistrate.Result<T_1>) => result is magistrate.Ok<T_1>;
};
interface TransformedValidator<T> extends Validator<T> {

@@ -41,8 +41,18 @@ }

type Infer<T> = T extends Validator<infer Type> ? Validator.ConvertOptional<Type> : never;
type PartialOpenAPISchema = Pick<OpenAPI.SchemaObject, 'title' | 'description' | 'deprecated' | 'example' | 'externalDocs'>;
interface Options<Type> {
defaultValue?: Type | (() => Type);
required: boolean;
nullable: boolean;
transform?: (value: any) => Promise<any> | any;
docs?: PartialOpenAPISchema;
}
}
declare abstract class Validator<T = unknown> {
static $rootKey: string;
protected readonly config: ValidatorOptions<T>;
protected readonly SubClass: new (...args: any[]) => Validator;
constructor();
protected readonly config: Validator.Options<T>;
static toDocument(validator: Validator): OpenAPI.ParameterBaseObject;
static validate(validator: Validator, value: any, key?: string, superKeys?: string[]): Promise<ValidateResult<any>>;
static validate(validator: Validator, value: any, key?: string, superKeys?: string[]): Promise<magistrate.Result<any>>;
static isEmpty(validator: Validator, value: any): boolean;

@@ -52,3 +62,3 @@ /**

*/
docs(docs: PartialOpenAPISchema): this;
docs(docs: Validator.PartialOpenAPISchema): this;
/**

@@ -68,3 +78,3 @@ * Value can be `undefined`,`null`,`''` or `KEY_NOT_EXIST`, and replace value to `undefined` by default.

/**
* 验证成功后的回调函数,支持异步操作,返回的数据被作为最终数据。
* A final callback while validation succeed. Transform value to any you expected.
*/

@@ -76,23 +86,28 @@ protected transform<T1>(fn: (value: any) => Promise<T1> | T1): Validator;

protected default(value: any): Validator;
protected validate(value: any, key: string, superKeys: string[]): Promise<ValidateResult<any>>;
protected validate(value: any, key: string, superKeys: string[]): Promise<magistrate.Result<any>>;
protected isEmpty(value: any): boolean;
protected isValidNull(value: any): boolean;
protected getDefaultValue<T = any>(value: any): T | undefined;
protected abstract validateValue(value: any, key: string, superKeys: string[]): Promise<ValidateResult<any>> | ValidateResult<any>;
protected abstract validateValue(value: any, key: string, superKeys: string[]): Promise<magistrate.Result<any>> | magistrate.Result<any>;
protected copy(): Validator;
protected copyConfig(prev: Validator): this;
protected toDocument(): OpenAPI.SchemaObject;
}
interface NumberValidatorOptions<T = false> extends ValidatorOptions<T> {
min?: number;
minInclusive?: boolean;
max?: number;
maxInclusive?: boolean;
onlyInteger?: boolean;
precision?: number;
declare namespace BaseNumberValidator {
interface Options<T = false> extends Validator.Options<T> {
min?: number;
minInclusive?: boolean;
max?: number;
maxInclusive?: boolean;
onlyInteger?: boolean;
precision?: number;
}
}
declare abstract class BaseNumberValidator<T = number> extends Validator<T> {
protected config: NumberValidatorOptions<T>;
protected config: BaseNumberValidator.Options<T>;
min(min: number, inclusive?: boolean): this;
max(max: number, inclusive?: boolean): this;
protected validateValue(num: number, key: string, superKeys: string[]): ValidateResult<number>;
protected validateValue(num: number, key: string, superKeys: string[]): magistrate.Result<number>;
protected copy: () => BaseNumberValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -112,11 +127,13 @@ }

interface BaseStringValidatorOptions<T> extends ValidatorOptions<T> {
trim?: boolean;
pattern?: RegExp;
lengthRange?: LengthRange;
declare namespace BaseStringValidator {
interface Options<T> extends Validator.Options<T> {
trim?: boolean;
pattern?: RegExp;
lengthRange?: LengthRange;
}
}
declare abstract class BaseStringValidator<T> extends Validator<T> {
protected config: BaseStringValidatorOptions<T>;
declare abstract class BaseStringValidator<T = string> extends Validator<T> {
protected config: BaseStringValidator.Options<T>;
/**
* Get read of spaces before validation
* Get rid of spaces before validation
*/

@@ -127,14 +144,9 @@ trim(): this;

protected getTrimValue(value: string): string;
protected shouldMatchPattern(value: string, key: string, superKeys: string[]): ValidateResult<string> | void;
protected shouldBetweenLength(value: string, key: string, superKeys: string[]): ValidateResult<string> | void;
protected shouldBeString(value: string, key: string, superKeys: string[]): ValidateResult<string> | void;
protected shouldMatchPattern(value: string, key: string, superKeys: string[]): magistrate.Result<string> | void;
protected shouldBetweenLength(value: string, key: string, superKeys: string[]): magistrate.Result<string> | void;
protected shouldBeString(value: string, key: string, superKeys: string[]): magistrate.Result<string> | void;
protected copy: () => BaseStringValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;
}
declare const magistrate: {
ok: <T>(result: T) => ValidateResult<T>;
fail: (message: string, key: string, superKeys: string[]) => ValidateResult<any>;
noError: <T_1>(result: ValidateResult<T_1>) => result is ValidateResultOK<T_1>;
};
declare class ValidatorError extends Error {

@@ -153,3 +165,3 @@ }

throwIfError: false;
}): Promise<ValidateResult<Validator.Infer<T>>>;
}): Promise<magistrate.Result<Validator.Infer<T>>>;
declare function validate<T extends {

@@ -166,3 +178,3 @@ [key: string]: V;

throwIfError: false;
}): Promise<ValidateResult<{
}): Promise<magistrate.Result<{
[K in keyof T]: Validator.Infer<T[K]>;

@@ -179,17 +191,19 @@ }>>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(value: any): ValidateResult<any>;
protected validateValue(value: any): magistrate.Result<any>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface ArrayValidatorOptions<T> extends ValidatorOptions<T> {
itemValidator?: Validator;
lengthRange: {
min?: number;
max?: number;
};
force?: boolean | ((value: any) => boolean);
separator: string | RegExp;
declare namespace ArrayValidator {
interface Options<T> extends Validator.Options<T> {
itemValidator?: Validator;
lengthRange: {
min?: number;
max?: number;
};
force?: boolean | ((value: any) => boolean);
separator: string | RegExp;
}
}
declare class ArrayValidator<T = unknown[]> extends Validator<T> {
protected config: ArrayValidatorOptions<T>;
protected config: ArrayValidator.Options<T>;
constructor(validator?: Validator);

@@ -199,3 +213,3 @@ /**

*/
forceToArray(filter?: (value: any) => boolean): this;
forceToArray(filter?: (value: any) => boolean): ArrayValidator<T>;
/**

@@ -207,3 +221,3 @@ * The separate symbol for string when `force to array` is enabled. Defaults `\s*,\s*`

*/
separator(pattern: string | RegExp): this;
separator(pattern: string | RegExp): ArrayValidator<T>;
optional: () => ArrayValidator<T | Validator.TOptional>;

@@ -213,3 +227,4 @@ nullable: () => ArrayValidator<T | null>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(value: any, key: string, superKeys: string[]): Promise<ValidateResult<any[]>>;
protected validateValue(value: any, key: string, superKeys: string[]): Promise<magistrate.Result<any[]>>;
protected copy: () => ArrayValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -225,12 +240,14 @@ }

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(value: bigint, key: string, superKeys: string[]): ValidateResult<bigint>;
protected validateValue(value: bigint, key: string, superKeys: string[]): magistrate.Result<bigint>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface BooleanValidatorOptions<T> extends ValidatorOptions<T> {
trueValues?: any[];
falseValues?: any[];
declare namespace BooleanValidator {
interface Options<T> extends Validator.Options<T> {
trueValues?: any[];
falseValues?: any[];
}
}
declare class BooleanValidator<T = boolean> extends Validator<T> {
protected config: BooleanValidatorOptions<T>;
protected config: BooleanValidator.Options<T>;
optional: () => BooleanValidator<T | Validator.TOptional>;

@@ -247,3 +264,3 @@ nullable: () => BooleanValidator<T | null>;

*/
trueValues(values: any[]): this;
trueValues(values: any[]): BooleanValidator<T>;
/**

@@ -256,11 +273,14 @@ * Set false values. Defaults `[0, '0', false, 'false']`

*/
falseValues(values: any[]): this;
protected validateValue(value: any, key: string, superKeys: string[]): ValidateResult<boolean>;
falseValues(values: any[]): BooleanValidator<T>;
protected validateValue(value: any, key: string, superKeys: string[]): magistrate.Result<boolean>;
protected copy: () => BooleanValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface BufferValidatorOptions<T = Buffer> extends ValidatorOptions<T> {
declare namespace BufferValidator {
interface Options<T = Buffer> extends Validator.Options<T> {
}
}
declare class BufferValidator<T = Buffer> extends Validator<T> {
protected config: BufferValidatorOptions<T>;
protected config: BufferValidator.Options<T>;
optional: () => BufferValidator<T | Validator.TOptional>;

@@ -270,11 +290,13 @@ nullable: () => BufferValidator<T | null>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(value: any, key: string, superKeys: string[]): ValidateResult<Buffer>;
protected validateValue(value: any, key: string, superKeys: string[]): magistrate.Result<Buffer>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface EmailValidatorOptions<T> extends BaseStringValidatorOptions<T> {
lengthRange?: LengthRange;
declare namespace EmailValidator {
interface Options<T> extends BaseStringValidator.Options<T> {
lengthRange?: LengthRange;
}
}
declare class EmailValidator<T = string> extends BaseStringValidator<T> {
protected config: EmailValidatorOptions<T>;
protected config: EmailValidator.Options<T>;
optional: () => EmailValidator<T | Validator.TOptional>;

@@ -285,3 +307,3 @@ nullable: () => EmailValidator<T | null>;

match: (pattern: RegExp) => this;
protected validateValue(email: string, key: string, superKeys: string[]): ValidateResult<string>;
protected validateValue(email: string, key: string, superKeys: string[]): magistrate.Result<string>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -292,8 +314,10 @@ }

interface EnumValidatorOptions<T> extends ValidatorOptions<T> {
ranges: T[];
declare namespace EnumValidator {
interface Options<T> extends Validator.Options<T> {
ranges: T[];
}
}
declare class EnumValidator<T = never> extends Validator<T> {
protected config: EnumValidatorOptions<T>;
constructor(ranges: T[]);
protected config: EnumValidator.Options<T>;
constructor(ranges?: T[]);
optional: () => EnumValidator<T | Validator.TOptional>;

@@ -303,11 +327,11 @@ nullable: () => EnumValidator<T | null>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(value: any, key: string, superKeys: string[]): ValidateResult<any>;
protected validateValue(value: any, key: string, superKeys: string[]): magistrate.Result<any>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface HashValidatorOptions<T> extends BaseStringValidatorOptions<T> {
algorithm: HashValidator.Algorithm;
}
declare namespace HashValidator {
type Algorithm = keyof typeof HashValidator.algorithmLength;
interface Options<T> extends BaseStringValidator.Options<T> {
algorithm: HashValidator.Algorithm;
}
}

@@ -334,3 +358,3 @@ declare class HashValidator<T = string> extends BaseStringValidator<T> {

static algorithmPattern: Record<string, RegExp>;
protected config: HashValidatorOptions<T>;
protected config: HashValidator.Options<T>;
constructor(algorithm: HashValidator.Algorithm);

@@ -341,3 +365,3 @@ optional: () => HashValidator<T | Validator.TOptional>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected validateValue(hash: string, key: string, superKeys: string[]): ValidateResult<string>;
protected validateValue(hash: string, key: string, superKeys: string[]): magistrate.Result<string>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -347,3 +371,3 @@ }

declare class IntValidator<T = number> extends BaseNumberValidator<T> {
protected config: NumberValidatorOptions<T>;
protected config: BaseNumberValidator.Options<T>;
constructor();

@@ -358,7 +382,7 @@ optional: () => IntValidator<T | Validator.TOptional>;

declare const versions: readonly ["v4", "v6"];
interface IpValidatorOptions<T> extends BaseStringValidatorOptions<T> {
ipVersion: IpValidator.Version[];
}
declare namespace IpValidator {
type Version = (typeof versions)[number];
interface Options<T> extends BaseStringValidator.Options<T> {
ipVersion: IpValidator.Version[];
}
}

@@ -369,3 +393,3 @@ declare class IpValidator<T = string> extends BaseStringValidator<T> {

};
protected config: IpValidatorOptions<T>;
protected config: IpValidator.Options<T>;
constructor(version: IpValidator.Version[]);

@@ -377,3 +401,3 @@ optional: () => IpValidator<T | Validator.TOptional>;

match: (pattern: RegExp) => this;
protected validateValue(ip: string, key: string, superKeys: string[]): ValidateResult<string>;
protected validateValue(ip: string, key: string, superKeys: string[]): magistrate.Result<string>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -383,3 +407,3 @@ }

declare class NumberValidator<T = number> extends BaseNumberValidator<T> {
protected config: NumberValidatorOptions<T>;
protected config: BaseNumberValidator.Options<T>;
optional: () => NumberValidator<T | Validator.TOptional>;

@@ -389,14 +413,17 @@ nullable: () => NumberValidator<T | null>;

transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
precision(maxDecimals: number): this;
precision(maxDecimals: number): NumberValidator<T>;
protected copy: () => NumberValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;
}
type ObjectProperty = Record<string, Validator>;
interface ObjectValidatorOptions<T> extends ValidatorOptions<T> {
properties?: ObjectProperty;
stringToObject?: boolean;
declare namespace ObjectValidator {
type Property = Record<string, Validator>;
interface Options<T> extends Validator.Options<T> {
properties?: Property;
stringToObject?: boolean;
}
}
declare class ObjectValidator<T = Validator.TObject> extends Validator<T> {
protected config: ObjectValidatorOptions<T>;
constructor(properties?: ObjectProperty);
protected config: ObjectValidator.Options<T>;
constructor(properties?: ObjectValidator.Property);
optional: () => ObjectValidator<T | Validator.TOptional>;

@@ -407,27 +434,32 @@ nullable: () => ObjectValidator<T | null>;

/**
* 当数据为字符串时,是否尝试使用`JSON.parse`解析。默认:`false`
* Try to parse data from string by built-in function `JSON.parse`. Defaults `false`
*/
parseFromString(is?: boolean): this;
parseFromString(is?: boolean): ObjectValidator<T>;
protected isPlainObject(value: any): value is object;
protected validateValue(origin: Record<string, any>, key: string, superKeys: string[]): Promise<ValidateResult<object>>;
protected validateValue(origin: Record<string, any>, key: string, superKeys: string[]): Promise<magistrate.Result<object>>;
protected copy: () => ObjectValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface OneOfValidatorOptions<T> extends ValidatorOptions<T> {
validators: Validator[];
declare namespace OneOfValidator {
interface Options<T> extends Validator.Options<T> {
validators: Validator[];
}
}
declare class OneOfValidator<T = never> extends Validator<T> {
protected config: OneOfValidatorOptions<T>;
protected config: OneOfValidator.Options<T>;
constructor(rules: Validator[]);
transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
protected isEmpty(_: any): boolean;
protected validateValue(value: any, key: string, superKeys: string[]): Promise<ValidateResult<any>>;
protected validateValue(value: any, key: string, superKeys: string[]): Promise<magistrate.Result<any>>;
protected toDocument(): OpenAPI.SchemaObject;
}
interface StringValidatorOptions<T> extends BaseStringValidatorOptions<T> {
allowEmpty?: boolean;
declare namespace StringValidator {
interface Options<T> extends BaseStringValidator.Options<T> {
allowEmpty?: boolean;
}
}
declare class StringValidator<T = string> extends BaseStringValidator<T> {
protected config: StringValidatorOptions<T>;
protected config: StringValidator.Options<T>;
optional: () => StringValidator<T | Validator.TOptional>;

@@ -441,6 +473,7 @@ nullable: () => StringValidator<T | null>;

*/
allowEmpty(): this;
allowEmpty(): StringValidator<T>;
trim: () => this;
protected isEmpty(value: any): boolean;
protected validateValue(value: string, key: string, superKeys: string[]): ValidateResult<string>;
protected validateValue(value: string, key: string, superKeys: string[]): magistrate.Result<string>;
protected copy: () => StringValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;

@@ -451,7 +484,7 @@ }

interface UuidValidatorOptions<T = string> extends BaseStringValidatorOptions<T> {
uuidVersion: UuidValidator.Version[];
}
declare namespace UuidValidator {
type Version = (typeof UuidValidator.versions)[number];
interface Options<T = string> extends BaseStringValidator.Options<T> {
uuidVersion: Version[];
}
}

@@ -463,3 +496,3 @@ declare class UuidValidator<T = string> extends BaseStringValidator<T> {

};
protected config: UuidValidatorOptions<T>;
protected config: UuidValidator.Options<T>;
constructor(versions: UuidValidator.Version[]);

@@ -471,6 +504,29 @@ optional: () => UuidValidator<T | Validator.TOptional>;

match: (pattern: RegExp) => this;
protected validateValue(uuid: string, key: string, superKeys: string[]): ValidateResult<string>;
protected validateValue(uuid: string, key: string, superKeys: string[]): magistrate.Result<string>;
protected toDocument(): OpenAPI.SchemaObject;
}
declare namespace DateTimeValidator {
interface Options<T = Date> extends Validator.Options<T> {
min?: () => Date;
minInclusive?: boolean;
max?: () => Date;
maxInclusive?: boolean;
}
}
declare class DateTimeValidator<T = Date> extends Validator<T> {
protected config: DateTimeValidator.Options<T>;
optional: () => DateTimeValidator<T | Validator.TOptional>;
nullable: () => DateTimeValidator<T | null>;
default: (date: Validator.ParameterOrFn<Date>) => DateTimeValidator<T | Validator.TDefault>;
transform: <T1>(fn: Validator.TransformFn<T, T1>) => TransformedValidator<T1>;
min(freshDate: () => Date, inclusive?: boolean): DateTimeValidator<T>;
max(freshDate: () => Date, inclusive?: boolean): DateTimeValidator<T>;
protected validateValue(value: any, key: string, superKeys: string[]): magistrate.Result<Date>;
protected toDate(value: any): false | Date;
protected compare(date: Date): boolean;
protected copy: () => DateTimeValidator<T>;
protected toDocument(): OpenAPI.SchemaObject;
}
declare class Rule {

@@ -568,5 +624,6 @@ static register<T extends Rule, K extends keyof T>(this: new (...args: any[]) => T, name: K, SubValidator: new (...args: any[]) => Validator): void;

uuid(versions: [UuidValidator.Version, ...UuidValidator.Version[]]): UuidValidator<string>;
dateTime(): DateTimeValidator<Date>;
}
declare const rule: Rule;
export { AnyValidator, ArrayValidator, BaseNumberValidator, BaseStringValidator, BaseStringValidatorOptions, BigIntValidator, BooleanValidator, BufferValidator, EmailValidator, EnumValidator, HashValidator, IntValidator, IpValidator, LengthRange, MixinLength, NumberValidator, NumberValidatorOptions, ObjectValidator, OneOfValidator, PartialOpenAPISchema, Rule, StringValidator, TransformedValidator, UuidValidator, ValidateOptions, ValidateResult, ValidateResultError, ValidateResultOK, Validator, ValidatorError, ValidatorOptions, magistrate, mixinLength, rule, validate };
export { AnyValidator, ArrayValidator, BaseNumberValidator, BaseStringValidator, BigIntValidator, BooleanValidator, BufferValidator, DateTimeValidator, EmailValidator, EnumValidator, HashValidator, IntValidator, IpValidator, LengthRange, MixinLength, NumberValidator, ObjectValidator, OneOfValidator, Rule, StringValidator, TransformedValidator, UuidValidator, ValidateOptions, Validator, ValidatorError, magistrate, mixinLength, rule, validate };

@@ -10,2 +10,6 @@ var __defProp = Object.defineProperty;

var Validator = class {
SubClass;
constructor() {
this.SubClass = new.target;
}
config = {

@@ -47,4 +51,5 @@ required: true,

docs(docs) {
this.config.docs = docs;
return this;
const validator = this.copy();
validator.config.docs = docs;
return validator;
}

@@ -59,4 +64,5 @@ /**

optional() {
this.config.required = false;
return this;
const validator = this.copy();
validator.config.required = false;
return validator;
}

@@ -68,11 +74,13 @@ /**

nullable() {
this.config.nullable = true;
return this;
const validator = this.copy();
validator.config.nullable = true;
return validator;
}
/**
* 验证成功后的回调函数,支持异步操作,返回的数据被作为最终数据。
* A final callback while validation succeed. Transform value to any you expected.
*/
transform(fn) {
this.config.transform = fn;
return this;
const validator = this.copy();
validator.config.transform = fn;
return validator;
}

@@ -83,5 +91,6 @@ /**

default(value) {
this.optional();
this.config.defaultValue = value;
return this;
const validator = this.copy();
validator.config.required = false;
validator.config.defaultValue = value;
return validator;
}

@@ -120,2 +129,9 @@ async validate(value, key, superKeys) {

}
copy() {
return new this.SubClass().copyConfig(this);
}
copyConfig(prev) {
this.config = { ...prev.config };
return this;
}
toDocument() {

@@ -130,5 +146,3 @@ return {};

ok: (result) => {
return {
ok: result
};
return { ok: result };
},

@@ -154,10 +168,12 @@ fail: (message, key, superKeys) => {

min(min, inclusive = true) {
this.config.min = min;
this.config.minInclusive = inclusive;
return this;
const validator = this.copy();
validator.config.min = min;
validator.config.minInclusive = inclusive;
return validator;
}
max(max, inclusive = true) {
this.config.max = max;
this.config.maxInclusive = inclusive;
return this;
const validator = this.copy();
validator.config.max = max;
validator.config.maxInclusive = inclusive;
return validator;
}

@@ -209,11 +225,13 @@ validateValue(num, key, superKeys) {

/**
* Get read of spaces before validation
* Get rid of spaces before validation
*/
trim() {
this.config.trim = true;
return this;
const validator = this.copy();
validator.config.trim = true;
return validator;
}
match(pattern) {
this.config.pattern = pattern;
return this;
const validator = this.copy();
validator.config.pattern = pattern;
return validator;
}

@@ -291,4 +309,5 @@ isEmpty(value) {

validator.prototype["length"] = function(min, max) {
this.config[configKey] = getLengthRange(min, max);
return this;
const validator2 = this.copy();
validator2.config[configKey] = getLengthRange(min, max);
return validator2;
};

@@ -298,11 +317,5 @@ }

if (typeof min === "number") {
return {
min,
max: typeof max === "number" ? max : min
};
return { min, max: typeof max === "number" ? max : min };
}
return {
min: typeof min.min === "number" ? min.min : 0,
max: min.max
};
return { min: typeof min.min === "number" ? min.min : 0, max: min.max };
};

@@ -321,4 +334,5 @@

forceToArray(filter) {
this.config.force = filter || true;
return this;
const validator = this.copy();
validator.config.force = filter || true;
return validator;
}

@@ -332,4 +346,5 @@ /**

separator(pattern) {
this.config.separator = pattern;
return this;
const validator = this.copy();
validator.config.separator = pattern;
return validator;
}

@@ -435,4 +450,5 @@ async validateValue(value, key, superKeys) {

trueValues(values) {
this.config.trueValues = values;
return this;
const validator = this.copy();
validator.config.trueValues = values;
return validator;
}

@@ -447,4 +463,5 @@ /**

falseValues(values) {
this.config.falseValues = values;
return this;
const validator = this.copy();
validator.config.falseValues = values;
return validator;
}

@@ -517,3 +534,3 @@ validateValue(value, key, superKeys) {

var EnumValidator = class extends Validator {
constructor(ranges) {
constructor(ranges = []) {
super();

@@ -676,4 +693,5 @@ this.config.ranges = ranges;

precision(maxDecimals) {
this.config.precision = Math.min(20, Math.max(0, maxDecimals));
return this;
const validator = this.copy();
validator.config.precision = Math.min(20, Math.max(0, maxDecimals));
return validator;
}

@@ -695,7 +713,8 @@ toDocument() {

/**
* 当数据为字符串时,是否尝试使用`JSON.parse`解析。默认:`false`
* Try to parse data from string by built-in function `JSON.parse`. Defaults `false`
*/
parseFromString(is = true) {
this.config.stringToObject = is;
return this;
const validator = this.copy();
validator.config.stringToObject = is;
return validator;
}

@@ -803,4 +822,5 @@ isPlainObject(value) {

allowEmpty() {
this.config.allowEmpty = true;
return this;
const validator = this.copy();
validator.config.allowEmpty = true;
return validator;
}

@@ -894,2 +914,58 @@ isEmpty(value) {

// src/validators/date-time-validator.ts
var DateTimeValidator = class extends Validator {
min(freshDate, inclusive = true) {
const validator = this.copy();
validator.config.min = freshDate;
validator.config.minInclusive = inclusive;
return validator;
}
max(freshDate, inclusive = true) {
const validator = this.copy();
validator.config.max = freshDate;
validator.config.maxInclusive = inclusive;
return validator;
}
validateValue(value, key, superKeys) {
const date = this.toDate(value);
if (date === false) {
return magistrate.fail("must be date", key, superKeys);
}
if (!this.compare(date)) {
return magistrate.fail("not in date range", key, superKeys);
}
return magistrate.ok(date);
}
toDate(value) {
if (value instanceof Date) {
if (value.toString() !== "Invalid Date") {
return new Date(value);
}
} else if (typeof value === "string") {
const date = new Date(value);
if (date.toString() !== "Invalid Date") {
return date;
}
}
return false;
}
compare(date) {
const { min, minInclusive, max, maxInclusive } = this.config;
const timestamp = +date;
if (min !== void 0 && (minInclusive ? timestamp < +min() : timestamp <= +min())) {
return false;
}
if (max !== void 0 && (maxInclusive ? timestamp > +max() : timestamp >= +max())) {
return false;
}
return true;
}
toDocument() {
return {
type: "string",
format: "date-time"
};
}
};
// src/api/validate.ts

@@ -964,3 +1040,3 @@ async function validate(source, schema, options2) {

enum(ranges) {
return new EnumValidator(ranges);
return new EnumValidator(toArray(ranges, true));
}

@@ -1026,2 +1102,5 @@ hash(algorithm) {

}
dateTime() {
return new DateTimeValidator();
}
};

@@ -1037,2 +1116,3 @@ var rule = new Rule();

BufferValidator,
DateTimeValidator,
EmailValidator,

@@ -1039,0 +1119,0 @@ EnumValidator,

{
"name": "@aomex/validator",
"version": "0.0.12",
"version": "0.0.13",
"description": "",

@@ -5,0 +5,0 @@ "type": "module",

Sorry, the diff of this file is not supported yet

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