1
This commit is contained in:
+44
@@ -0,0 +1,44 @@
|
||||
import type { InternalRuleItem, InternalValidateMessages, RuleItem, RuleType, Rules, SyncErrorType, ValidateCallback, ValidateMessages, ValidateOption, Values } from './interface';
|
||||
export * from './interface';
|
||||
/**
|
||||
* Encapsulates a validation schema.
|
||||
*
|
||||
* @param descriptor An object declaring validation rules
|
||||
* for this schema.
|
||||
*/
|
||||
declare class Schema {
|
||||
static register: (type: string, validator: any) => void;
|
||||
static warning: (type: string, errors: SyncErrorType[]) => void;
|
||||
static messages: InternalValidateMessages;
|
||||
static validators: {
|
||||
string: import("./interface").ExecuteValidator;
|
||||
method: import("./interface").ExecuteValidator;
|
||||
number: import("./interface").ExecuteValidator;
|
||||
boolean: import("./interface").ExecuteValidator;
|
||||
regexp: import("./interface").ExecuteValidator;
|
||||
integer: import("./interface").ExecuteValidator;
|
||||
float: import("./interface").ExecuteValidator;
|
||||
array: import("./interface").ExecuteValidator;
|
||||
object: import("./interface").ExecuteValidator;
|
||||
enum: import("./interface").ExecuteValidator;
|
||||
pattern: import("./interface").ExecuteValidator;
|
||||
date: import("./interface").ExecuteValidator;
|
||||
url: import("./interface").ExecuteValidator;
|
||||
hex: import("./interface").ExecuteValidator;
|
||||
email: import("./interface").ExecuteValidator;
|
||||
tel: import("./interface").ExecuteValidator;
|
||||
required: import("./interface").ExecuteValidator;
|
||||
any: import("./interface").ExecuteValidator;
|
||||
};
|
||||
rules: Record<string, RuleItem[]>;
|
||||
_messages: InternalValidateMessages;
|
||||
constructor(descriptor: Rules);
|
||||
define(rules: Rules): void;
|
||||
messages(messages?: ValidateMessages): InternalValidateMessages;
|
||||
validate(source: Values, option?: ValidateOption, callback?: ValidateCallback): Promise<Values>;
|
||||
validate(source: Values, callback: ValidateCallback): Promise<Values>;
|
||||
validate(source: Values): Promise<Values>;
|
||||
getType(rule: InternalRuleItem): RuleType;
|
||||
getValidationMethod(rule: InternalRuleItem): ((rule: InternalRuleItem, value: any, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | import("./interface").SyncValidateResult) | import("./interface").ExecuteValidator;
|
||||
}
|
||||
export default Schema;
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
|
||||
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
|
||||
import _typeof from "@babel/runtime/helpers/esm/typeof";
|
||||
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
|
||||
import _createClass from "@babel/runtime/helpers/esm/createClass";
|
||||
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
|
||||
import { messages as defaultMessages, newMessages } from "./messages";
|
||||
import { asyncMap, complementError, convertFieldsError, deepMerge, format, warning } from "./util";
|
||||
import validators from "./validator/index";
|
||||
export * from "./interface";
|
||||
|
||||
/**
|
||||
* Encapsulates a validation schema.
|
||||
*
|
||||
* @param descriptor An object declaring validation rules
|
||||
* for this schema.
|
||||
*/
|
||||
var Schema = /*#__PURE__*/function () {
|
||||
function Schema(descriptor) {
|
||||
_classCallCheck(this, Schema);
|
||||
// ======================== Instance ========================
|
||||
_defineProperty(this, "rules", null);
|
||||
_defineProperty(this, "_messages", defaultMessages);
|
||||
this.define(descriptor);
|
||||
}
|
||||
_createClass(Schema, [{
|
||||
key: "define",
|
||||
value: function define(rules) {
|
||||
var _this = this;
|
||||
if (!rules) {
|
||||
throw new Error('Cannot configure a schema with no rules');
|
||||
}
|
||||
if (_typeof(rules) !== 'object' || Array.isArray(rules)) {
|
||||
throw new Error('Rules must be an object');
|
||||
}
|
||||
this.rules = {};
|
||||
Object.keys(rules).forEach(function (name) {
|
||||
var item = rules[name];
|
||||
_this.rules[name] = Array.isArray(item) ? item : [item];
|
||||
});
|
||||
}
|
||||
}, {
|
||||
key: "messages",
|
||||
value: function messages(_messages) {
|
||||
if (_messages) {
|
||||
this._messages = deepMerge(newMessages(), _messages);
|
||||
}
|
||||
return this._messages;
|
||||
}
|
||||
}, {
|
||||
key: "validate",
|
||||
value: function validate(source_) {
|
||||
var _this2 = this;
|
||||
var o = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
var oc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
|
||||
var source = source_;
|
||||
var options = o;
|
||||
var callback = oc;
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
if (!this.rules || Object.keys(this.rules).length === 0) {
|
||||
if (callback) {
|
||||
callback(null, source);
|
||||
}
|
||||
return Promise.resolve(source);
|
||||
}
|
||||
function complete(results) {
|
||||
var errors = [];
|
||||
var fields = {};
|
||||
function add(e) {
|
||||
if (Array.isArray(e)) {
|
||||
var _errors;
|
||||
errors = (_errors = errors).concat.apply(_errors, _toConsumableArray(e));
|
||||
} else {
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < results.length; i++) {
|
||||
add(results[i]);
|
||||
}
|
||||
if (!errors.length) {
|
||||
callback(null, source);
|
||||
} else {
|
||||
fields = convertFieldsError(errors);
|
||||
callback(errors, fields);
|
||||
}
|
||||
}
|
||||
if (options.messages) {
|
||||
var messages = this.messages();
|
||||
if (messages === defaultMessages) {
|
||||
messages = newMessages();
|
||||
}
|
||||
deepMerge(messages, options.messages);
|
||||
options.messages = messages;
|
||||
} else {
|
||||
options.messages = this.messages();
|
||||
}
|
||||
var series = {};
|
||||
var keys = options.keys || Object.keys(this.rules);
|
||||
keys.forEach(function (z) {
|
||||
var arr = _this2.rules[z];
|
||||
var value = source[z];
|
||||
arr.forEach(function (r) {
|
||||
var rule = r;
|
||||
if (typeof rule.transform === 'function') {
|
||||
if (source === source_) {
|
||||
source = _objectSpread({}, source);
|
||||
}
|
||||
value = source[z] = rule.transform(value);
|
||||
if (value !== undefined && value !== null) {
|
||||
rule.type = rule.type || (Array.isArray(value) ? 'array' : _typeof(value));
|
||||
}
|
||||
}
|
||||
if (typeof rule === 'function') {
|
||||
rule = {
|
||||
validator: rule
|
||||
};
|
||||
} else {
|
||||
rule = _objectSpread({}, rule);
|
||||
}
|
||||
|
||||
// Fill validator. Skip if nothing need to validate
|
||||
rule.validator = _this2.getValidationMethod(rule);
|
||||
if (!rule.validator) {
|
||||
return;
|
||||
}
|
||||
rule.field = z;
|
||||
rule.fullField = rule.fullField || z;
|
||||
rule.type = _this2.getType(rule);
|
||||
series[z] = series[z] || [];
|
||||
series[z].push({
|
||||
rule: rule,
|
||||
value: value,
|
||||
source: source,
|
||||
field: z
|
||||
});
|
||||
});
|
||||
});
|
||||
var errorFields = {};
|
||||
return asyncMap(series, options, function (data, doIt) {
|
||||
var rule = data.rule;
|
||||
var deep = (rule.type === 'object' || rule.type === 'array') && (_typeof(rule.fields) === 'object' || _typeof(rule.defaultField) === 'object');
|
||||
deep = deep && (rule.required || !rule.required && data.value);
|
||||
rule.field = data.field;
|
||||
function addFullField(key, schema) {
|
||||
return _objectSpread(_objectSpread({}, schema), {}, {
|
||||
fullField: "".concat(rule.fullField, ".").concat(key),
|
||||
fullFields: rule.fullFields ? [].concat(_toConsumableArray(rule.fullFields), [key]) : [key]
|
||||
});
|
||||
}
|
||||
function cb() {
|
||||
var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
|
||||
var errorList = Array.isArray(e) ? e : [e];
|
||||
if (!options.suppressWarning && errorList.length) {
|
||||
Schema.warning('async-validator:', errorList);
|
||||
}
|
||||
if (errorList.length && rule.message !== undefined && rule.message !== null) {
|
||||
errorList = [].concat(rule.message);
|
||||
}
|
||||
|
||||
// Fill error info
|
||||
var filledErrors = errorList.map(complementError(rule, source));
|
||||
if (options.first && filledErrors.length) {
|
||||
errorFields[rule.field] = 1;
|
||||
return doIt(filledErrors);
|
||||
}
|
||||
if (!deep) {
|
||||
doIt(filledErrors);
|
||||
} else {
|
||||
// if rule is required but the target object
|
||||
// does not exist fail at the rule level and don't
|
||||
// go deeper
|
||||
if (rule.required && !data.value) {
|
||||
if (rule.message !== undefined) {
|
||||
filledErrors = [].concat(rule.message).map(complementError(rule, source));
|
||||
} else if (options.error) {
|
||||
filledErrors = [options.error(rule, format(options.messages.required, rule.field))];
|
||||
}
|
||||
return doIt(filledErrors);
|
||||
}
|
||||
var fieldsSchema = {};
|
||||
if (rule.defaultField) {
|
||||
Object.keys(data.value).map(function (key) {
|
||||
fieldsSchema[key] = rule.defaultField;
|
||||
});
|
||||
}
|
||||
fieldsSchema = _objectSpread(_objectSpread({}, fieldsSchema), data.rule.fields);
|
||||
var paredFieldsSchema = {};
|
||||
Object.keys(fieldsSchema).forEach(function (field) {
|
||||
var fieldSchema = fieldsSchema[field];
|
||||
var fieldSchemaList = Array.isArray(fieldSchema) ? fieldSchema : [fieldSchema];
|
||||
paredFieldsSchema[field] = fieldSchemaList.map(addFullField.bind(null, field));
|
||||
});
|
||||
var schema = new Schema(paredFieldsSchema);
|
||||
schema.messages(options.messages);
|
||||
if (data.rule.options) {
|
||||
data.rule.options.messages = options.messages;
|
||||
data.rule.options.error = options.error;
|
||||
}
|
||||
schema.validate(data.value, data.rule.options || options, function (errs) {
|
||||
var finalErrors = [];
|
||||
if (filledErrors && filledErrors.length) {
|
||||
finalErrors.push.apply(finalErrors, _toConsumableArray(filledErrors));
|
||||
}
|
||||
if (errs && errs.length) {
|
||||
finalErrors.push.apply(finalErrors, _toConsumableArray(errs));
|
||||
}
|
||||
doIt(finalErrors.length ? finalErrors : null);
|
||||
});
|
||||
}
|
||||
}
|
||||
var res;
|
||||
if (rule.asyncValidator) {
|
||||
res = rule.asyncValidator(rule, data.value, cb, data.source, options);
|
||||
} else if (rule.validator) {
|
||||
try {
|
||||
res = rule.validator(rule, data.value, cb, data.source, options);
|
||||
} catch (error) {
|
||||
var _console$error, _console;
|
||||
(_console$error = (_console = console).error) === null || _console$error === void 0 || _console$error.call(_console, error);
|
||||
// rethrow to report error
|
||||
if (!options.suppressValidatorError) {
|
||||
setTimeout(function () {
|
||||
throw error;
|
||||
}, 0);
|
||||
}
|
||||
cb(error.message);
|
||||
}
|
||||
if (res === true) {
|
||||
cb();
|
||||
} else if (res === false) {
|
||||
cb(typeof rule.message === 'function' ? rule.message(rule.fullField || rule.field) : rule.message || "".concat(rule.fullField || rule.field, " fails"));
|
||||
} else if (res instanceof Array) {
|
||||
cb(res);
|
||||
} else if (res instanceof Error) {
|
||||
cb(res.message);
|
||||
}
|
||||
}
|
||||
if (res && res.then) {
|
||||
res.then(function () {
|
||||
return cb();
|
||||
}, function (e) {
|
||||
return cb(e);
|
||||
});
|
||||
}
|
||||
}, function (results) {
|
||||
complete(results);
|
||||
}, source);
|
||||
}
|
||||
}, {
|
||||
key: "getType",
|
||||
value: function getType(rule) {
|
||||
if (rule.type === undefined && rule.pattern instanceof RegExp) {
|
||||
rule.type = 'pattern';
|
||||
}
|
||||
if (typeof rule.validator !== 'function' && rule.type && !validators.hasOwnProperty(rule.type)) {
|
||||
throw new Error(format('Unknown rule type %s', rule.type));
|
||||
}
|
||||
return rule.type || 'string';
|
||||
}
|
||||
}, {
|
||||
key: "getValidationMethod",
|
||||
value: function getValidationMethod(rule) {
|
||||
if (typeof rule.validator === 'function') {
|
||||
return rule.validator;
|
||||
}
|
||||
var keys = Object.keys(rule);
|
||||
var messageIndex = keys.indexOf('message');
|
||||
if (messageIndex !== -1) {
|
||||
keys.splice(messageIndex, 1);
|
||||
}
|
||||
if (keys.length === 1 && keys[0] === 'required') {
|
||||
return validators.required;
|
||||
}
|
||||
return validators[this.getType(rule)] || undefined;
|
||||
}
|
||||
}]);
|
||||
return Schema;
|
||||
}();
|
||||
// ========================= Static =========================
|
||||
_defineProperty(Schema, "register", function register(type, validator) {
|
||||
if (typeof validator !== 'function') {
|
||||
throw new Error('Cannot register a validator by type, validator is not a function');
|
||||
}
|
||||
validators[type] = validator;
|
||||
});
|
||||
_defineProperty(Schema, "warning", warning);
|
||||
_defineProperty(Schema, "messages", defaultMessages);
|
||||
_defineProperty(Schema, "validators", validators);
|
||||
export default Schema;
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
export type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'array' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email' | 'tel' | 'pattern' | 'any';
|
||||
export interface ValidateOption {
|
||||
suppressWarning?: boolean;
|
||||
suppressValidatorError?: boolean;
|
||||
first?: boolean;
|
||||
firstFields?: boolean | string[];
|
||||
messages?: Partial<ValidateMessages>;
|
||||
/** The name of rules need to be trigger. Will validate all rules if leave empty */
|
||||
keys?: string[];
|
||||
error?: (rule: InternalRuleItem, message: string) => ValidateError;
|
||||
}
|
||||
export type SyncErrorType = Error | string;
|
||||
export type SyncValidateResult = boolean | SyncErrorType | SyncErrorType[];
|
||||
export type ValidateResult = void | Promise<void> | SyncValidateResult;
|
||||
export interface RuleItem {
|
||||
type?: RuleType;
|
||||
required?: boolean;
|
||||
pattern?: RegExp | string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
len?: number;
|
||||
enum?: (string | number | boolean | null | undefined)[];
|
||||
whitespace?: boolean;
|
||||
fields?: Record<string, Rule>;
|
||||
options?: ValidateOption;
|
||||
defaultField?: Rule;
|
||||
transform?: (value: Value) => Value;
|
||||
message?: string | ((a?: string) => string);
|
||||
asyncValidator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | Promise<void>;
|
||||
validator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => SyncValidateResult | void;
|
||||
}
|
||||
export type Rule = RuleItem | RuleItem[];
|
||||
export type Rules = Record<string, Rule>;
|
||||
/**
|
||||
* Rule for validating a value exists in an enumerable list.
|
||||
*
|
||||
* @param rule The validation rule.
|
||||
* @param value The value of the field on the source object.
|
||||
* @param source The source object being validated.
|
||||
* @param errors An array of errors that this rule may add
|
||||
* validation errors to.
|
||||
* @param options The validation options.
|
||||
* @param options.messages The validation messages.
|
||||
* @param type Rule type
|
||||
*/
|
||||
export type ExecuteRule = (rule: InternalRuleItem, value: Value, source: Values, errors: string[], options: ValidateOption, type?: string) => void;
|
||||
/**
|
||||
* Performs validation for any type.
|
||||
*
|
||||
* @param rule The validation rule.
|
||||
* @param value The value of the field on the source object.
|
||||
* @param callback The callback function.
|
||||
* @param source The source object being validated.
|
||||
* @param options The validation options.
|
||||
* @param options.messages The validation messages.
|
||||
*/
|
||||
export type ExecuteValidator = (rule: InternalRuleItem, value: Value, callback: (error?: string[]) => void, source: Values, options: ValidateOption) => void;
|
||||
type ValidateMessage<T extends any[] = unknown[]> = string | ((...args: T) => string);
|
||||
type FullField = string | undefined;
|
||||
type EnumString = string | undefined;
|
||||
type Pattern = string | RegExp | undefined;
|
||||
type Range = number | undefined;
|
||||
type Type = string | undefined;
|
||||
export interface ValidateMessages {
|
||||
default?: ValidateMessage;
|
||||
required?: ValidateMessage<[FullField]>;
|
||||
enum?: ValidateMessage<[FullField, EnumString]>;
|
||||
whitespace?: ValidateMessage<[FullField]>;
|
||||
date?: {
|
||||
format?: ValidateMessage;
|
||||
parse?: ValidateMessage;
|
||||
invalid?: ValidateMessage;
|
||||
};
|
||||
types?: {
|
||||
string?: ValidateMessage<[FullField, Type]>;
|
||||
method?: ValidateMessage<[FullField, Type]>;
|
||||
array?: ValidateMessage<[FullField, Type]>;
|
||||
object?: ValidateMessage<[FullField, Type]>;
|
||||
number?: ValidateMessage<[FullField, Type]>;
|
||||
date?: ValidateMessage<[FullField, Type]>;
|
||||
boolean?: ValidateMessage<[FullField, Type]>;
|
||||
integer?: ValidateMessage<[FullField, Type]>;
|
||||
float?: ValidateMessage<[FullField, Type]>;
|
||||
regexp?: ValidateMessage<[FullField, Type]>;
|
||||
email?: ValidateMessage<[FullField, Type]>;
|
||||
tel?: ValidateMessage<[FullField, Type]>;
|
||||
url?: ValidateMessage<[FullField, Type]>;
|
||||
hex?: ValidateMessage<[FullField, Type]>;
|
||||
};
|
||||
string?: {
|
||||
len?: ValidateMessage<[FullField, Range]>;
|
||||
min?: ValidateMessage<[FullField, Range]>;
|
||||
max?: ValidateMessage<[FullField, Range]>;
|
||||
range?: ValidateMessage<[FullField, Range, Range]>;
|
||||
};
|
||||
number?: {
|
||||
len?: ValidateMessage<[FullField, Range]>;
|
||||
min?: ValidateMessage<[FullField, Range]>;
|
||||
max?: ValidateMessage<[FullField, Range]>;
|
||||
range?: ValidateMessage<[FullField, Range, Range]>;
|
||||
};
|
||||
array?: {
|
||||
len?: ValidateMessage<[FullField, Range]>;
|
||||
min?: ValidateMessage<[FullField, Range]>;
|
||||
max?: ValidateMessage<[FullField, Range]>;
|
||||
range?: ValidateMessage<[FullField, Range, Range]>;
|
||||
};
|
||||
pattern?: {
|
||||
mismatch?: ValidateMessage<[FullField, Value, Pattern]>;
|
||||
};
|
||||
}
|
||||
export interface InternalValidateMessages extends ValidateMessages {
|
||||
clone: () => InternalValidateMessages;
|
||||
}
|
||||
export type Value = any;
|
||||
export type Values = Record<string, Value>;
|
||||
export interface ValidateError {
|
||||
message?: string;
|
||||
fieldValue?: Value;
|
||||
field?: string;
|
||||
}
|
||||
export type ValidateFieldsError = Record<string, ValidateError[]>;
|
||||
export type ValidateCallback = (errors: ValidateError[] | null, fields: ValidateFieldsError | Values) => void;
|
||||
export interface RuleValuePackage {
|
||||
rule: InternalRuleItem;
|
||||
value: Value;
|
||||
source: Values;
|
||||
field: string;
|
||||
}
|
||||
export interface InternalRuleItem extends Omit<RuleItem, 'validator'> {
|
||||
field?: string;
|
||||
fullField?: string;
|
||||
fullFields?: string[];
|
||||
validator?: RuleItem['validator'] | ExecuteValidator;
|
||||
}
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { InternalValidateMessages } from './interface';
|
||||
export declare function newMessages(): InternalValidateMessages;
|
||||
export declare const messages: InternalValidateMessages;
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
export function newMessages() {
|
||||
return {
|
||||
default: 'Validation error on field %s',
|
||||
required: '%s is required',
|
||||
enum: '%s must be one of %s',
|
||||
whitespace: '%s cannot be empty',
|
||||
date: {
|
||||
format: '%s date %s is invalid for format %s',
|
||||
parse: '%s date could not be parsed, %s is invalid ',
|
||||
invalid: '%s date %s is invalid'
|
||||
},
|
||||
types: {
|
||||
string: '%s is not a %s',
|
||||
method: '%s is not a %s (function)',
|
||||
array: '%s is not an %s',
|
||||
object: '%s is not an %s',
|
||||
number: '%s is not a %s',
|
||||
date: '%s is not a %s',
|
||||
boolean: '%s is not a %s',
|
||||
integer: '%s is not an %s',
|
||||
float: '%s is not a %s',
|
||||
regexp: '%s is not a valid %s',
|
||||
email: '%s is not a valid %s',
|
||||
tel: '%s is not a valid %s',
|
||||
url: '%s is not a valid %s',
|
||||
hex: '%s is not a valid %s'
|
||||
},
|
||||
string: {
|
||||
len: '%s must be exactly %s characters',
|
||||
min: '%s must be at least %s characters',
|
||||
max: '%s cannot be longer than %s characters',
|
||||
range: '%s must be between %s and %s characters'
|
||||
},
|
||||
number: {
|
||||
len: '%s must equal %s',
|
||||
min: '%s cannot be less than %s',
|
||||
max: '%s cannot be greater than %s',
|
||||
range: '%s must be between %s and %s'
|
||||
},
|
||||
array: {
|
||||
len: '%s must be exactly %s in length',
|
||||
min: '%s cannot be less than %s in length',
|
||||
max: '%s cannot be greater than %s in length',
|
||||
range: '%s must be between %s and %s in length'
|
||||
},
|
||||
pattern: {
|
||||
mismatch: '%s value %s does not match pattern %s'
|
||||
},
|
||||
clone: function clone() {
|
||||
var cloned = JSON.parse(JSON.stringify(this));
|
||||
cloned.clone = this.clone;
|
||||
return cloned;
|
||||
}
|
||||
};
|
||||
}
|
||||
export var messages = newMessages();
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
declare const enumerable: ExecuteRule;
|
||||
export default enumerable;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import { format } from "../util";
|
||||
var ENUM = 'enum';
|
||||
var enumerable = function enumerable(rule, value, source, errors, options) {
|
||||
rule[ENUM] = Array.isArray(rule[ENUM]) ? rule[ENUM] : [];
|
||||
if (rule[ENUM].indexOf(value) === -1) {
|
||||
errors.push(format(options.messages[ENUM], rule.fullField, rule[ENUM].join(', ')));
|
||||
}
|
||||
};
|
||||
export default enumerable;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
declare const _default: {
|
||||
required: import("../interface").ExecuteRule;
|
||||
whitespace: import("../interface").ExecuteRule;
|
||||
type: import("../interface").ExecuteRule;
|
||||
range: import("../interface").ExecuteRule;
|
||||
enum: import("../interface").ExecuteRule;
|
||||
pattern: import("../interface").ExecuteRule;
|
||||
};
|
||||
export default _default;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import enumRule from "./enum";
|
||||
import pattern from "./pattern";
|
||||
import range from "./range";
|
||||
import required from "./required";
|
||||
import type from "./type";
|
||||
import whitespace from "./whitespace";
|
||||
export default {
|
||||
required: required,
|
||||
whitespace: whitespace,
|
||||
type: type,
|
||||
range: range,
|
||||
enum: enumRule,
|
||||
pattern: pattern
|
||||
};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
declare const pattern: ExecuteRule;
|
||||
export default pattern;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { format } from "../util";
|
||||
var pattern = function pattern(rule, value, source, errors, options) {
|
||||
if (rule.pattern) {
|
||||
if (rule.pattern instanceof RegExp) {
|
||||
// if a RegExp instance is passed, reset `lastIndex` in case its `global`
|
||||
// flag is accidentally set to `true`, which in a validation scenario
|
||||
// is not necessary and the result might be misleading
|
||||
rule.pattern.lastIndex = 0;
|
||||
if (!rule.pattern.test(value)) {
|
||||
errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
|
||||
}
|
||||
} else if (typeof rule.pattern === 'string') {
|
||||
var _pattern = new RegExp(rule.pattern);
|
||||
if (!_pattern.test(value)) {
|
||||
errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
export default pattern;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
declare const range: ExecuteRule;
|
||||
export default range;
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { format } from "../util";
|
||||
var range = function range(rule, value, source, errors, options) {
|
||||
var len = typeof rule.len === 'number';
|
||||
var min = typeof rule.min === 'number';
|
||||
var max = typeof rule.max === 'number';
|
||||
// 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
|
||||
var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
||||
var val = value;
|
||||
var key = null;
|
||||
var num = typeof value === 'number';
|
||||
var str = typeof value === 'string';
|
||||
var arr = Array.isArray(value);
|
||||
if (num) {
|
||||
key = 'number';
|
||||
} else if (str) {
|
||||
key = 'string';
|
||||
} else if (arr) {
|
||||
key = 'array';
|
||||
}
|
||||
// if the value is not of a supported type for range validation
|
||||
// the validation rule rule should use the
|
||||
// type property to also test for a particular type
|
||||
if (!key) {
|
||||
return false;
|
||||
}
|
||||
if (arr) {
|
||||
val = value.length;
|
||||
}
|
||||
if (str) {
|
||||
// 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".length !== 3
|
||||
val = value.replace(spRegexp, '_').length;
|
||||
}
|
||||
if (len) {
|
||||
if (val !== rule.len) {
|
||||
errors.push(format(options.messages[key].len, rule.fullField, rule.len));
|
||||
}
|
||||
} else if (min && !max && val < rule.min) {
|
||||
errors.push(format(options.messages[key].min, rule.fullField, rule.min));
|
||||
} else if (max && !min && val > rule.max) {
|
||||
errors.push(format(options.messages[key].max, rule.fullField, rule.max));
|
||||
} else if (min && max && (val < rule.min || val > rule.max)) {
|
||||
errors.push(format(options.messages[key].range, rule.fullField, rule.min, rule.max));
|
||||
}
|
||||
};
|
||||
export default range;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
declare const required: ExecuteRule;
|
||||
export default required;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { format, isEmptyValue } from "../util";
|
||||
var required = function required(rule, value, source, errors, options, type) {
|
||||
if (rule.required && (!source.hasOwnProperty(rule.field) || isEmptyValue(value, type || rule.type))) {
|
||||
errors.push(format(options.messages.required, rule.fullField));
|
||||
}
|
||||
};
|
||||
export default required;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
declare const type: ExecuteRule;
|
||||
export default type;
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import _typeof from "@babel/runtime/helpers/esm/typeof";
|
||||
import { format } from "../util";
|
||||
import required from "./required";
|
||||
import getUrlRegex from "./url";
|
||||
/* eslint max-len:0 */
|
||||
|
||||
var pattern = {
|
||||
// http://emailregex.com/
|
||||
email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/,
|
||||
// url: new RegExp(
|
||||
// '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
|
||||
// 'i',
|
||||
// ),
|
||||
/**
|
||||
* Phone number regex, support country code, brackets, spaces, and dashes (or non-breaking hyphen \u2011).
|
||||
* @see https://regexr.com/3c53v
|
||||
* @see https://ihateregex.io/expr/phone/
|
||||
* @see https://developers.google.com/style/phone-numbers using non-breaking hyphen \u2011
|
||||
*/
|
||||
tel: /^(\+[0-9]{1,3}[-\s\u2011]?)?(\([0-9]{1,4}\)[-\s\u2011]?)?([0-9]+[-\s\u2011]?)*[0-9]+$/,
|
||||
hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i
|
||||
};
|
||||
var types = {
|
||||
integer: function integer(value) {
|
||||
return types.number(value) && parseInt(value, 10) === value;
|
||||
},
|
||||
float: function float(value) {
|
||||
return types.number(value) && !types.integer(value);
|
||||
},
|
||||
array: function array(value) {
|
||||
return Array.isArray(value);
|
||||
},
|
||||
regexp: function regexp(value) {
|
||||
if (value instanceof RegExp) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
return !!new RegExp(value);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
date: function date(value) {
|
||||
return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear === 'function' && !isNaN(value.getTime());
|
||||
},
|
||||
number: function number(value) {
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
}
|
||||
return typeof value === 'number';
|
||||
},
|
||||
object: function object(value) {
|
||||
return _typeof(value) === 'object' && !types.array(value);
|
||||
},
|
||||
method: function method(value) {
|
||||
return typeof value === 'function';
|
||||
},
|
||||
email: function email(value) {
|
||||
return typeof value === 'string' && value.length <= 320 && !!value.match(pattern.email);
|
||||
},
|
||||
tel: function tel(value) {
|
||||
return typeof value === 'string' && value.length <= 32 && !!value.match(pattern.tel);
|
||||
},
|
||||
url: function url(value) {
|
||||
return typeof value === 'string' && value.length <= 2048 && !!value.match(getUrlRegex());
|
||||
},
|
||||
hex: function hex(value) {
|
||||
return typeof value === 'string' && !!value.match(pattern.hex);
|
||||
}
|
||||
};
|
||||
var type = function type(rule, value, source, errors, options) {
|
||||
if (rule.required && value === undefined) {
|
||||
required(rule, value, source, errors, options);
|
||||
return;
|
||||
}
|
||||
var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'tel', 'number', 'date', 'url', 'hex'];
|
||||
var ruleType = rule.type;
|
||||
if (custom.indexOf(ruleType) > -1) {
|
||||
if (!types[ruleType](value)) {
|
||||
errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
|
||||
}
|
||||
// straight typeof check
|
||||
} else if (ruleType && _typeof(value) !== rule.type) {
|
||||
errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
|
||||
}
|
||||
};
|
||||
export default type;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
declare const _default: () => RegExp;
|
||||
export default _default;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
// https://github.com/kevva/url-regex/blob/master/index.js
|
||||
var urlReg;
|
||||
export default (function () {
|
||||
if (urlReg) {
|
||||
return urlReg;
|
||||
}
|
||||
var word = '[a-fA-F\\d:]';
|
||||
var b = function b(options) {
|
||||
return options && options.includeBoundaries ? "(?:(?<=\\s|^)(?=".concat(word, ")|(?<=").concat(word, ")(?=\\s|$))") : '';
|
||||
};
|
||||
var v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';
|
||||
var v6seg = '[a-fA-F\\d]{1,4}';
|
||||
var v6List = ["(?:".concat(v6seg, ":){7}(?:").concat(v6seg, "|:)"), // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
||||
"(?:".concat(v6seg, ":){6}(?:").concat(v4, "|:").concat(v6seg, "|:)"), // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::
|
||||
"(?:".concat(v6seg, ":){5}(?::").concat(v4, "|(?::").concat(v6seg, "){1,2}|:)"), // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::
|
||||
"(?:".concat(v6seg, ":){4}(?:(?::").concat(v6seg, "){0,1}:").concat(v4, "|(?::").concat(v6seg, "){1,3}|:)"), // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::
|
||||
"(?:".concat(v6seg, ":){3}(?:(?::").concat(v6seg, "){0,2}:").concat(v4, "|(?::").concat(v6seg, "){1,4}|:)"), // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::
|
||||
"(?:".concat(v6seg, ":){2}(?:(?::").concat(v6seg, "){0,3}:").concat(v4, "|(?::").concat(v6seg, "){1,5}|:)"), // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::
|
||||
"(?:".concat(v6seg, ":){1}(?:(?::").concat(v6seg, "){0,4}:").concat(v4, "|(?::").concat(v6seg, "){1,6}|:)"), // 1:: 1::3:4:5:6:7:8 1::8 1::
|
||||
"(?::(?:(?::".concat(v6seg, "){0,5}:").concat(v4, "|(?::").concat(v6seg, "){1,7}|:))") // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
|
||||
];
|
||||
var v6Eth0 = "(?:%[0-9a-zA-Z]{1,})?"; // %eth0 %1
|
||||
|
||||
var v6 = "(?:".concat(v6List.join('|'), ")").concat(v6Eth0);
|
||||
|
||||
// Pre-compile only the exact regexes because adding a global flag make regexes stateful
|
||||
var v46Exact = new RegExp("(?:^".concat(v4, "$)|(?:^").concat(v6, "$)"));
|
||||
var v4exact = new RegExp("^".concat(v4, "$"));
|
||||
var v6exact = new RegExp("^".concat(v6, "$"));
|
||||
var ip = function ip(options) {
|
||||
return options && options.exact ? v46Exact : new RegExp("(?:".concat(b(options)).concat(v4).concat(b(options), ")|(?:").concat(b(options)).concat(v6).concat(b(options), ")"), 'g');
|
||||
};
|
||||
ip.v4 = function (options) {
|
||||
return options && options.exact ? v4exact : new RegExp("".concat(b(options)).concat(v4).concat(b(options)), 'g');
|
||||
};
|
||||
ip.v6 = function (options) {
|
||||
return options && options.exact ? v6exact : new RegExp("".concat(b(options)).concat(v6).concat(b(options)), 'g');
|
||||
};
|
||||
var protocol = "(?:(?:[a-z]+:)?//)";
|
||||
var auth = '(?:\\S+(?::\\S*)?@)?';
|
||||
var ipv4 = ip.v4().source;
|
||||
var ipv6 = ip.v6().source;
|
||||
var host = "(?:(?:[a-z\\u00a1-\\uffff0-9][-_]*)*[a-z\\u00a1-\\uffff0-9]+)";
|
||||
var domain = "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*";
|
||||
var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
|
||||
var port = '(?::\\d{2,5})?';
|
||||
var path = '(?:[/?#][^\\s"]*)?';
|
||||
var regex = "(?:".concat(protocol, "|www\\.)").concat(auth, "(?:localhost|").concat(ipv4, "|").concat(ipv6, "|").concat(host).concat(domain).concat(tld, ")").concat(port).concat(path);
|
||||
urlReg = new RegExp("(?:^".concat(regex, "$)"), 'i');
|
||||
return urlReg;
|
||||
});
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
import type { ExecuteRule } from '../interface';
|
||||
/**
|
||||
* Rule for validating whitespace.
|
||||
*
|
||||
* @param rule The validation rule.
|
||||
* @param value The value of the field on the source object.
|
||||
* @param source The source object being validated.
|
||||
* @param errors An array of errors that this rule may add
|
||||
* validation errors to.
|
||||
* @param options The validation options.
|
||||
* @param options.messages The validation messages.
|
||||
*/
|
||||
declare const whitespace: ExecuteRule;
|
||||
export default whitespace;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { format } from "../util";
|
||||
|
||||
/**
|
||||
* Rule for validating whitespace.
|
||||
*
|
||||
* @param rule The validation rule.
|
||||
* @param value The value of the field on the source object.
|
||||
* @param source The source object being validated.
|
||||
* @param errors An array of errors that this rule may add
|
||||
* validation errors to.
|
||||
* @param options The validation options.
|
||||
* @param options.messages The validation messages.
|
||||
*/
|
||||
var whitespace = function whitespace(rule, value, source, errors, options) {
|
||||
if (/^\s+$/.test(value) || value === '') {
|
||||
errors.push(format(options.messages.whitespace, rule.fullField));
|
||||
}
|
||||
};
|
||||
export default whitespace;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { InternalRuleItem, RuleValuePackage, SyncErrorType, ValidateError, ValidateOption, Value, Values } from './interface';
|
||||
export declare let warning: (type: string, errors: SyncErrorType[]) => void;
|
||||
export declare function convertFieldsError(errors: ValidateError[]): Record<string, ValidateError[]>;
|
||||
export declare function format(template: ((...args: any[]) => string) | string, ...args: any[]): string;
|
||||
export declare function isEmptyValue(value: Value, type?: string): boolean;
|
||||
export declare function isEmptyObject(obj: object): boolean;
|
||||
export declare class AsyncValidationError extends Error {
|
||||
errors: ValidateError[];
|
||||
fields: Record<string, ValidateError[]>;
|
||||
constructor(errors: ValidateError[], fields: Record<string, ValidateError[]>);
|
||||
}
|
||||
type ValidateFunc = (data: RuleValuePackage, doIt: (errors: ValidateError[]) => void) => void;
|
||||
export declare function asyncMap(objArr: Record<string, RuleValuePackage[]>, option: ValidateOption, func: ValidateFunc, callback: (errors: ValidateError[]) => void, source: Values): Promise<Values>;
|
||||
export declare function complementError(rule: InternalRuleItem, source: Values): (oe: ValidateError | (() => string) | string) => ValidateError;
|
||||
export declare function deepMerge<T extends object>(target: T, source: Partial<T>): T;
|
||||
export {};
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
|
||||
import _typeof from "@babel/runtime/helpers/esm/typeof";
|
||||
import _createClass from "@babel/runtime/helpers/esm/createClass";
|
||||
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
|
||||
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
|
||||
import _inherits from "@babel/runtime/helpers/esm/inherits";
|
||||
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
|
||||
import _wrapNativeSuper from "@babel/runtime/helpers/esm/wrapNativeSuper";
|
||||
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
|
||||
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
|
||||
/* eslint no-console:0 */
|
||||
|
||||
var formatRegExp = /%[sdj%]/g;
|
||||
export var warning = function warning() {};
|
||||
|
||||
// don't print warning message when in production env or node runtime
|
||||
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && typeof document !== 'undefined') {
|
||||
warning = function warning(type, errors) {
|
||||
if (typeof console !== 'undefined' && console.warn && typeof ASYNC_VALIDATOR_NO_WARNING === 'undefined') {
|
||||
if (errors.every(function (e) {
|
||||
return typeof e === 'string';
|
||||
})) {
|
||||
console.warn(type, errors);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export function convertFieldsError(errors) {
|
||||
if (!errors || !errors.length) return null;
|
||||
var fields = {};
|
||||
errors.forEach(function (error) {
|
||||
var field = error.field;
|
||||
fields[field] = fields[field] || [];
|
||||
fields[field].push(error);
|
||||
});
|
||||
return fields;
|
||||
}
|
||||
export function format(template) {
|
||||
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
||||
args[_key - 1] = arguments[_key];
|
||||
}
|
||||
var i = 0;
|
||||
var len = args.length;
|
||||
if (typeof template === 'function') {
|
||||
// eslint-disable-next-line prefer-spread
|
||||
return template.apply(null, args);
|
||||
}
|
||||
if (typeof template === 'string') {
|
||||
var str = template.replace(formatRegExp, function (x) {
|
||||
if (x === '%%') {
|
||||
return '%';
|
||||
}
|
||||
if (i >= len) {
|
||||
return x;
|
||||
}
|
||||
switch (x) {
|
||||
case '%s':
|
||||
return String(args[i++]);
|
||||
case '%d':
|
||||
return Number(args[i++]);
|
||||
case '%j':
|
||||
try {
|
||||
return JSON.stringify(args[i++]);
|
||||
} catch (_) {
|
||||
return '[Circular]';
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return x;
|
||||
}
|
||||
});
|
||||
return str;
|
||||
}
|
||||
return template;
|
||||
}
|
||||
function isNativeStringType(type) {
|
||||
return type === 'string' || type === 'url' || type === 'hex' || type === 'email' || type === 'date' || type === 'pattern' || type === 'tel';
|
||||
}
|
||||
export function isEmptyValue(value, type) {
|
||||
if (value === undefined || value === null) {
|
||||
return true;
|
||||
}
|
||||
if (type === 'array' && Array.isArray(value) && !value.length) {
|
||||
return true;
|
||||
}
|
||||
if (isNativeStringType(type) && typeof value === 'string' && !value) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function isEmptyObject(obj) {
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
function asyncParallelArray(arr, func, callback) {
|
||||
var results = [];
|
||||
var total = 0;
|
||||
var arrLength = arr.length;
|
||||
function count(errors) {
|
||||
results.push.apply(results, _toConsumableArray(errors || []));
|
||||
total++;
|
||||
if (total === arrLength) {
|
||||
callback(results);
|
||||
}
|
||||
}
|
||||
arr.forEach(function (a) {
|
||||
func(a, count);
|
||||
});
|
||||
}
|
||||
function asyncSerialArray(arr, func, callback) {
|
||||
var index = 0;
|
||||
var arrLength = arr.length;
|
||||
function next(errors) {
|
||||
if (errors && errors.length) {
|
||||
callback(errors);
|
||||
return;
|
||||
}
|
||||
var original = index;
|
||||
index = index + 1;
|
||||
if (original < arrLength) {
|
||||
func(arr[original], next);
|
||||
} else {
|
||||
callback([]);
|
||||
}
|
||||
}
|
||||
next([]);
|
||||
}
|
||||
function flattenObjArr(objArr) {
|
||||
var ret = [];
|
||||
Object.keys(objArr).forEach(function (k) {
|
||||
ret.push.apply(ret, _toConsumableArray(objArr[k] || []));
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
export var AsyncValidationError = /*#__PURE__*/function (_Error) {
|
||||
_inherits(AsyncValidationError, _Error);
|
||||
var _super = _createSuper(AsyncValidationError);
|
||||
function AsyncValidationError(errors, fields) {
|
||||
var _this;
|
||||
_classCallCheck(this, AsyncValidationError);
|
||||
_this = _super.call(this, 'Async Validation Error');
|
||||
_defineProperty(_assertThisInitialized(_this), "errors", void 0);
|
||||
_defineProperty(_assertThisInitialized(_this), "fields", void 0);
|
||||
_this.errors = errors;
|
||||
_this.fields = fields;
|
||||
return _this;
|
||||
}
|
||||
return _createClass(AsyncValidationError);
|
||||
}( /*#__PURE__*/_wrapNativeSuper(Error));
|
||||
export function asyncMap(objArr, option, func, callback, source) {
|
||||
if (option.first) {
|
||||
var _pending = new Promise(function (resolve, reject) {
|
||||
var next = function next(errors) {
|
||||
callback(errors);
|
||||
return errors.length ? reject(new AsyncValidationError(errors, convertFieldsError(errors))) : resolve(source);
|
||||
};
|
||||
var flattenArr = flattenObjArr(objArr);
|
||||
asyncSerialArray(flattenArr, func, next);
|
||||
});
|
||||
_pending.catch(function (e) {
|
||||
return e;
|
||||
});
|
||||
return _pending;
|
||||
}
|
||||
var firstFields = option.firstFields === true ? Object.keys(objArr) : option.firstFields || [];
|
||||
var objArrKeys = Object.keys(objArr);
|
||||
var objArrLength = objArrKeys.length;
|
||||
var total = 0;
|
||||
var results = [];
|
||||
var pending = new Promise(function (resolve, reject) {
|
||||
var next = function next(errors) {
|
||||
// eslint-disable-next-line prefer-spread
|
||||
results.push.apply(results, errors);
|
||||
total++;
|
||||
if (total === objArrLength) {
|
||||
callback(results);
|
||||
return results.length ? reject(new AsyncValidationError(results, convertFieldsError(results))) : resolve(source);
|
||||
}
|
||||
};
|
||||
if (!objArrKeys.length) {
|
||||
callback(results);
|
||||
resolve(source);
|
||||
}
|
||||
objArrKeys.forEach(function (key) {
|
||||
var arr = objArr[key];
|
||||
if (firstFields.indexOf(key) !== -1) {
|
||||
asyncSerialArray(arr, func, next);
|
||||
} else {
|
||||
asyncParallelArray(arr, func, next);
|
||||
}
|
||||
});
|
||||
});
|
||||
pending.catch(function (e) {
|
||||
return e;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
function isErrorObj(obj) {
|
||||
return !!(obj && obj.message !== undefined);
|
||||
}
|
||||
function getValue(value, path) {
|
||||
var v = value;
|
||||
for (var i = 0; i < path.length; i++) {
|
||||
if (v == undefined) {
|
||||
return v;
|
||||
}
|
||||
v = v[path[i]];
|
||||
}
|
||||
return v;
|
||||
}
|
||||
export function complementError(rule, source) {
|
||||
return function (oe) {
|
||||
var fieldValue;
|
||||
if (rule.fullFields) {
|
||||
fieldValue = getValue(source, rule.fullFields);
|
||||
} else {
|
||||
fieldValue = source[oe.field || rule.fullField];
|
||||
}
|
||||
if (isErrorObj(oe)) {
|
||||
oe.field = oe.field || rule.fullField;
|
||||
oe.fieldValue = fieldValue;
|
||||
return oe;
|
||||
}
|
||||
return {
|
||||
message: typeof oe === 'function' ? oe() : oe,
|
||||
fieldValue: fieldValue,
|
||||
field: oe.field || rule.fullField
|
||||
};
|
||||
};
|
||||
}
|
||||
export function deepMerge(target, source) {
|
||||
if (source) {
|
||||
for (var s in source) {
|
||||
if (source.hasOwnProperty(s)) {
|
||||
var value = source[s];
|
||||
if (_typeof(value) === 'object' && _typeof(target[s]) === 'object') {
|
||||
target[s] = _objectSpread(_objectSpread({}, target[s]), value);
|
||||
} else {
|
||||
target[s] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const any: ExecuteValidator;
|
||||
export default any;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var any = function any(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default any;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const array: ExecuteValidator;
|
||||
export default array;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule/index";
|
||||
var array = function array(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if ((value === undefined || value === null) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options, 'array');
|
||||
if (value !== undefined && value !== null) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
rules.range(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default array;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const boolean: ExecuteValidator;
|
||||
export default boolean;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var boolean = function boolean(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default boolean;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const date: ExecuteValidator;
|
||||
export default date;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var date = function date(rule, value, callback, source, options) {
|
||||
// console.log('integer rule called %j', rule);
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
// console.log('validate on %s value', value);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value, 'date') && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (!isEmptyValue(value, 'date')) {
|
||||
var dateObject;
|
||||
if (value instanceof Date) {
|
||||
dateObject = value;
|
||||
} else {
|
||||
dateObject = new Date(value);
|
||||
}
|
||||
rules.type(rule, dateObject, source, errors, options);
|
||||
if (dateObject) {
|
||||
rules.range(rule, dateObject.getTime(), source, errors, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default date;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const enumerable: ExecuteValidator;
|
||||
export default enumerable;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var ENUM = 'enum';
|
||||
var enumerable = function enumerable(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules[ENUM](rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default enumerable;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const floatFn: ExecuteValidator;
|
||||
export default floatFn;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var floatFn = function floatFn(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
rules.range(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default floatFn;
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
declare const _default: {
|
||||
string: import("../interface").ExecuteValidator;
|
||||
method: import("../interface").ExecuteValidator;
|
||||
number: import("../interface").ExecuteValidator;
|
||||
boolean: import("../interface").ExecuteValidator;
|
||||
regexp: import("../interface").ExecuteValidator;
|
||||
integer: import("../interface").ExecuteValidator;
|
||||
float: import("../interface").ExecuteValidator;
|
||||
array: import("../interface").ExecuteValidator;
|
||||
object: import("../interface").ExecuteValidator;
|
||||
enum: import("../interface").ExecuteValidator;
|
||||
pattern: import("../interface").ExecuteValidator;
|
||||
date: import("../interface").ExecuteValidator;
|
||||
url: import("../interface").ExecuteValidator;
|
||||
hex: import("../interface").ExecuteValidator;
|
||||
email: import("../interface").ExecuteValidator;
|
||||
tel: import("../interface").ExecuteValidator;
|
||||
required: import("../interface").ExecuteValidator;
|
||||
any: import("../interface").ExecuteValidator;
|
||||
};
|
||||
export default _default;
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import any from "./any";
|
||||
import array from "./array";
|
||||
import boolean from "./boolean";
|
||||
import date from "./date";
|
||||
import enumValidator from "./enum";
|
||||
import float from "./float";
|
||||
import integer from "./integer";
|
||||
import method from "./method";
|
||||
import number from "./number";
|
||||
import object from "./object";
|
||||
import pattern from "./pattern";
|
||||
import regexp from "./regexp";
|
||||
import required from "./required";
|
||||
import string from "./string";
|
||||
import type from "./type";
|
||||
export default {
|
||||
string: string,
|
||||
method: method,
|
||||
number: number,
|
||||
boolean: boolean,
|
||||
regexp: regexp,
|
||||
integer: integer,
|
||||
float: float,
|
||||
array: array,
|
||||
object: object,
|
||||
enum: enumValidator,
|
||||
pattern: pattern,
|
||||
date: date,
|
||||
url: type,
|
||||
hex: type,
|
||||
email: type,
|
||||
tel: type,
|
||||
required: required,
|
||||
any: any
|
||||
};
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const integer: ExecuteValidator;
|
||||
export default integer;
|
||||
Generated
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var integer = function integer(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
rules.range(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default integer;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const method: ExecuteValidator;
|
||||
export default method;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var method = function method(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default method;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const number: ExecuteValidator;
|
||||
export default number;
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var number = function number(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (value === '') {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
value = undefined;
|
||||
}
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
rules.range(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default number;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const object: ExecuteValidator;
|
||||
export default object;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var object = function object(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (value !== undefined) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default object;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const pattern: ExecuteValidator;
|
||||
export default pattern;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var pattern = function pattern(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value, 'string') && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (!isEmptyValue(value, 'string')) {
|
||||
rules.pattern(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default pattern;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const regexp: ExecuteValidator;
|
||||
export default regexp;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var regexp = function regexp(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options);
|
||||
if (!isEmptyValue(value)) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default regexp;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const required: ExecuteValidator;
|
||||
export default required;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import _typeof from "@babel/runtime/helpers/esm/typeof";
|
||||
import rules from "../rule";
|
||||
var required = function required(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var type = Array.isArray(value) ? 'array' : _typeof(value);
|
||||
rules.required(rule, value, source, errors, options, type);
|
||||
callback(errors);
|
||||
};
|
||||
export default required;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const string: ExecuteValidator;
|
||||
export default string;
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var string = function string(rule, value, callback, source, options) {
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value, 'string') && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options, 'string');
|
||||
if (!isEmptyValue(value, 'string')) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
rules.range(rule, value, source, errors, options);
|
||||
rules.pattern(rule, value, source, errors, options);
|
||||
if (rule.whitespace === true) {
|
||||
rules.whitespace(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default string;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { ExecuteValidator } from '../interface';
|
||||
declare const type: ExecuteValidator;
|
||||
export default type;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import rules from "../rule";
|
||||
import { isEmptyValue } from "../util";
|
||||
var type = function type(rule, value, callback, source, options) {
|
||||
var ruleType = rule.type;
|
||||
var errors = [];
|
||||
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
|
||||
if (validate) {
|
||||
if (isEmptyValue(value, ruleType) && !rule.required) {
|
||||
return callback();
|
||||
}
|
||||
rules.required(rule, value, source, errors, options, ruleType);
|
||||
if (!isEmptyValue(value, ruleType)) {
|
||||
rules.type(rule, value, source, errors, options);
|
||||
}
|
||||
}
|
||||
callback(errors);
|
||||
};
|
||||
export default type;
|
||||
Reference in New Issue
Block a user