add all frontend files

This commit is contained in:
2026-01-17 15:16:36 -05:00
parent ff16ae7858
commit e40287e4aa
25704 changed files with 1935289 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2014-present yiminghe
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

480
node_modules/@rc-component/async-validator/README.md generated vendored Normal file
View File

@@ -0,0 +1,480 @@
# @rc-component/async-validator
[![NPM version][npm-image]][npm-url]
[![npm download][download-image]][download-url]
[![build status][github-actions-image]][github-actions-url]
[![Codecov][codecov-image]][codecov-url]
[![dumi][dumi-image]][dumi-url]
[npm-image]: http://img.shields.io/npm/v/@rc-component/async-validator.svg?style=flat-square
[npm-url]: http://npmjs.org/package/@rc-component/async-validator
[travis-image]: https://img.shields.io/travis/react-component/async-validator/master?style=flat-square
[travis-url]: https://travis-ci.com/react-component/async-validator
[github-actions-image]: https://github.com/react-component/async-validator/actions/workflows/ci.yml/badge.svg
[github-actions-url]: https://github.com/react-component/async-validator/actions/workflows/ci.yml
[codecov-image]: https://img.shields.io/codecov/c/github/react-component/async-validator/master.svg?style=flat-square
[codecov-url]: https://app.codecov.io/gh/react-component/async-validator
[david-url]: https://david-dm.org/react-component/async-validator
[david-image]: https://david-dm.org/react-component/async-validator/status.svg?style=flat-square
[david-dev-url]: https://david-dm.org/react-component/async-validator?type=dev
[david-dev-image]: https://david-dm.org/react-component/async-validator/dev-status.svg?style=flat-square
[download-image]: https://img.shields.io/npm/dm/@rc-component/async-validator.svg?style=flat-square
[download-url]: https://npmjs.org/package/@rc-component/async-validator
[bundlephobia-url]: https://bundlephobia.com/package/@rc-component/async-validator
[bundlephobia-image]: https://badgen.net/bundlephobia/minzip/@rc-component/async-validator
[dumi-url]: https://github.com/umijs/dumi
[dumi-image]: https://img.shields.io/badge/docs%20by-dumi-blue?style=flat-square
Validate form asynchronous. A variation of https://github.com/freeformsystems/async-validate
## Install
```bash
npm i @rc-component/async-validator
```
## Usage
Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to the `validate` method of the schema:
```js
import Schema from '@rc-component/async-validator';
const descriptor = {
name: {
type: 'string',
required: true,
validator: (rule, value) => value === 'muji',
},
age: {
type: 'number',
asyncValidator: (rule, value) => {
return new Promise((resolve, reject) => {
if (value < 18) {
reject('too young'); // reject with error message
} else {
resolve();
}
});
},
},
};
const validator = new Schema(descriptor);
validator.validate({ name: 'muji' }, (errors, fields) => {
if (errors) {
// validation failed, errors is an array of all errors
// fields is an object keyed by field name with an array of
// errors per field
return handleErrors(errors, fields);
}
// validation passed
});
// PROMISE USAGE
validator
.validate({ name: 'muji', age: 16 })
.then(() => {
// validation passed or without error message
})
.catch(({ errors, fields }) => {
return handleErrors(errors, fields);
});
```
## API
### Validate
```js
function(source, [options], callback): Promise
```
- `source`: The object to validate (required).
- `options`: An object describing processing options for the validation (optional).
- `callback`: A callback function to invoke when validation completes (optional).
The method will return a Promise object like:
- `then()`validation passed
- `catch({ errors, fields })`validation failed, errors is an array of all errors, fields is an object keyed by field name with an array of errors per field
### Options
- `suppressWarning`: Boolean, whether to suppress internal warning about invalid value.
- `first`: Boolean, Invoke `callback` when the first validation rule generates an error,
no more validation rules are processed.
If your validation involves multiple asynchronous calls (for example, database queries) and you only need the first error use this option.
- `firstFields`: Boolean|String[], Invoke `callback` when the first validation rule of the specified field generates an error,
no more validation rules of the same field are processed. `true` means all fields.
### Rules
Rules may be functions that perform validation.
```js
function(rule, value, callback, source, options)
```
- `rule`: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a `field` property with the name of the field being validated.
- `value`: The value of the source object property being validated.
- `callback`: A callback function to invoke once validation is complete. It expects to be passed an array of `Error` instances to indicate validation failure. If the check is synchronous, you can directly return a `false` or `Error` or `Error Array`.
- `source`: The source object that was passed to the `validate` method.
- `options`: Additional options.
- `options.messages`: The object containing validation error messages, will be deep merged with defaultMessages.
The options passed to `validate` or `asyncValidate` are passed on to the validation functions so that you may reference transient data (such as model references) in validation functions. However, some option names are reserved; if you use these properties of the options object they are overwritten. The reserved properties are `messages`, `exception` and `error`.
```js
import Schema from '@rc-component/async-validator';
const descriptor = {
name(rule, value, callback, source, options) {
const errors = [];
if (!/^[a-z0-9]+$/.test(value)) {
errors.push(
new Error(util.format('%s must be lowercase alphanumeric characters', rule.field)),
);
}
return errors;
},
};
const validator = new Schema(descriptor);
validator.validate({ name: 'Firstname' }, (errors, fields) => {
if (errors) {
return handleErrors(errors, fields);
}
// validation passed
});
```
It is often useful to test against multiple validation rules for a single field, to do so make the rule an array of objects, for example:
```js
const descriptor = {
email: [
{ type: 'string', required: true, pattern: Schema.pattern.email },
{
validator(rule, value, callback, source, options) {
const errors = [];
// test if email address already exists in a database
// and add a validation error to the errors array if it does
return errors;
},
},
],
};
```
#### Type
Indicates the `type` of validator to use. Recognised type values are:
- `string`: Must be of type `string`. `This is the default type.`
- `number`: Must be of type `number`.
- `boolean`: Must be of type `boolean`.
- `method`: Must be of type `function`.
- `regexp`: Must be an instance of `RegExp` or a string that does not generate an exception when creating a new `RegExp`.
- `integer`: Must be of type `number` and an integer.
- `float`: Must be of type `number` and a floating point number.
- `array`: Must be an array as determined by `Array.isArray`.
- `object`: Must be of type `object` and not `Array.isArray`.
- `enum`: Value must exist in the `enum`.
- `date`: Value must be valid as determined by `Date`
- `url`: Must be of type `url`.
- `hex`: Must be of type `hex`.
- `email`: Must be of type `email`.
- `any`: Can be any type.
#### Required
The `required` rule property indicates that the field must exist on the source object being validated.
#### Pattern
The `pattern` rule property indicates a regular expression that the value must match to pass validation.
#### Range
A range is defined using the `min` and `max` properties. For `string` and `array` types comparison is performed against the `length`, for `number` types the number must not be less than `min` nor greater than `max`.
#### Length
To validate an exact length of a field specify the `len` property. For `string` and `array` types comparison is performed on the `length` property, for the `number` type this property indicates an exact match for the `number`, ie, it may only be strictly equal to `len`.
If the `len` property is combined with the `min` and `max` range properties, `len` takes precedence.
#### Enumerable
> Since version 3.0.0 if you want to validate the values `0` or `false` inside `enum` types, you have to include them explicitly.
To validate a value from a list of possible values use the `enum` type with a `enum` property listing the valid values for the field, for example:
```js
const descriptor = {
role: { type: 'enum', enum: ['admin', 'user', 'guest'] },
};
```
#### Whitespace
It is typical to treat required fields that only contain whitespace as errors. To add an additional test for a string that consists solely of whitespace add a `whitespace` property to a rule with a value of `true`. The rule must be a `string` type.
You may wish to sanitize user input instead of testing for whitespace, see [transform](#transform) for an example that would allow you to strip whitespace.
#### Deep Rules
If you need to validate deep object properties you may do so for validation rules that are of the `object` or `array` type by assigning nested rules to a `fields` property of the rule.
```js
const descriptor = {
address: {
type: 'object',
required: true,
fields: {
street: { type: 'string', required: true },
city: { type: 'string', required: true },
zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },
},
},
name: { type: 'string', required: true },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} }, (errors, fields) => {
// errors for address.street, address.city, address.zip
});
```
Note that if you do not specify the `required` property on the parent rule it is perfectly valid for the field not to be declared on the source object and the deep validation rules will not be executed as there is nothing to validate against.
Deep rule validation creates a schema for the nested rules so you can also specify the `options` passed to the `schema.validate()` method.
```js
const descriptor = {
address: {
type: 'object',
required: true,
options: { first: true },
fields: {
street: { type: 'string', required: true },
city: { type: 'string', required: true },
zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },
},
},
name: { type: 'string', required: true },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} }).catch(({ errors, fields }) => {
// now only errors for street and name
});
```
The parent rule is also validated so if you have a set of rules such as:
```js
const descriptor = {
roles: {
type: 'array',
required: true,
len: 3,
fields: {
0: { type: 'string', required: true },
1: { type: 'string', required: true },
2: { type: 'string', required: true },
},
},
};
```
And supply a source object of `{ roles: ['admin', 'user'] }` then two errors will be created. One for the array length mismatch and one for the missing required array entry at index 2.
#### defaultField
The `defaultField` property can be used with the `array` or `object` type for validating all values of the container.
It may be an `object` or `array` containing validation rules. For example:
```js
const descriptor = {
urls: {
type: 'array',
required: true,
defaultField: { type: 'url' },
},
};
```
Note that `defaultField` is expanded to `fields`, see [deep rules](#deep-rules).
#### Transform
Sometimes it is necessary to transform a value before validation, possibly to coerce the value or to sanitize it in some way. To do this add a `transform` function to the validation rule. The property is transformed prior to validation and returned as promise result or callback result when pass validation.
```js
import Schema from '@rc-component/async-validator';
const descriptor = {
name: {
type: 'string',
required: true,
pattern: /^[a-z]+$/,
transform(value) {
return value.trim();
},
},
};
const validator = new Schema(descriptor);
const source = { name: ' user ' };
validator.validate(source)
.then((data) => assert.equal(data.name, 'user'));
validator.validate(source,(errors, data)=>{
assert.equal(data.name, 'user'));
});
```
Without the `transform` function validation would fail due to the pattern not matching as the input contains leading and trailing whitespace, but by adding the transform function validation passes and the field value is sanitized at the same time.
#### Messages
Depending upon your application requirements, you may need i18n support or you may prefer different validation error messages.
The easiest way to achieve this is to assign a `message` to a rule:
```js
{ name: { type: 'string', required: true, message: 'Name is required' } }
```
Message can be any type, such as jsx format.
```js
{ name: { type: 'string', required: true, message: '<b>Name is required</b>' } }
```
Message can also be a function, e.g. if you use vue-i18n:
```js
{ name: { type: 'string', required: true, message: () => this.$t( 'name is required' ) } }
```
Potentially you may require the same schema validation rules for different languages, in which case duplicating the schema rules for each language does not make sense.
In this scenario you could just provide your own messages for the language and assign it to the schema:
```js
import Schema from '@rc-component/async-validator';
const cn = {
required: '%s 必填',
};
const descriptor = { name: { type: 'string', required: true } };
const validator = new Schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);
...
```
If you are defining your own validation functions it is better practice to assign the message strings to a messages object and then access the messages via the `options.messages` property within the validation function.
#### asyncValidator
You can customize the asynchronous validation function for the specified field:
```js
const fields = {
asyncField: {
asyncValidator(rule, value, callback) {
ajax({
url: 'xx',
value: value,
}).then(
function (data) {
callback();
},
function (error) {
callback(new Error(error));
},
);
},
},
promiseField: {
asyncValidator(rule, value) {
return ajax({
url: 'xx',
value: value,
});
},
},
};
```
#### validator
You can custom validate function for specified field:
```js
const fields = {
field: {
validator(rule, value, callback) {
return value === 'test';
},
message: 'Value is not equal to "test".',
},
field2: {
validator(rule, value, callback) {
return new Error(`${value} is not equal to 'test'.`);
},
},
arrField: {
validator(rule, value) {
return [new Error('Message 1'), new Error('Message 2')];
},
},
};
```
## FAQ
### How to avoid global warning
```js
import Schema from '@rc-component/async-validator';
Schema.warning = function () {};
```
or
```js
globalThis.ASYNC_VALIDATOR_NO_WARNING = 1;
```
### How to check if it is `true`
Use `enum` type passing `true` as option.
```js
{
type: 'enum',
enum: [true],
message: '',
}
```
## Test Case
```bash
npm test
```
## Coverage
```bash
npm run coverage
```
Open coverage/ dir
## License
Everything is [MIT](https://en.wikipedia.org/wiki/MIT_License).

View File

@@ -0,0 +1,43 @@
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;
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): import("./interface").ExecuteValidator | ((rule: InternalRuleItem, value: any, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | import("./interface").SyncValidateResult);
}
export default Schema;

292
node_modules/@rc-component/async-validator/es/index.js generated vendored Normal file
View File

@@ -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) {
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;

View File

@@ -0,0 +1,135 @@
export type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'array' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email' | '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]>;
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 {};

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,3 @@
import type { InternalValidateMessages } from './interface';
export declare function newMessages(): InternalValidateMessages;
export declare const messages: InternalValidateMessages;

View File

@@ -0,0 +1,55 @@
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',
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();

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const enumerable: ExecuteRule;
export default enumerable;

View File

@@ -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;

View File

@@ -0,0 +1,9 @@
declare const _default: {
required: import("..").ExecuteRule;
whitespace: import("..").ExecuteRule;
type: import("..").ExecuteRule;
range: import("..").ExecuteRule;
enum: import("..").ExecuteRule;
pattern: import("..").ExecuteRule;
};
export default _default;

View File

@@ -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
};

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const pattern: ExecuteRule;
export default pattern;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const range: ExecuteRule;
export default range;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const required: ExecuteRule;
export default required;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const type: ExecuteRule;
export default type;

View File

@@ -0,0 +1,77 @@
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',
// ),
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);
},
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', '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;

View File

@@ -0,0 +1,2 @@
declare const _default: () => RegExp;
export default _default;

View File

@@ -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;
});

View File

@@ -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;

View File

@@ -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;

View File

@@ -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
node_modules/@rc-component/async-validator/es/util.js generated vendored Normal file
View File

@@ -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';
}
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;
}

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const any: ExecuteValidator;
export default any;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const array: ExecuteValidator;
export default array;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const boolean: ExecuteValidator;
export default boolean;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const date: ExecuteValidator;
export default date;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const enumerable: ExecuteValidator;
export default enumerable;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const floatFn: ExecuteValidator;
export default floatFn;

View File

@@ -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;

View File

@@ -0,0 +1,20 @@
declare const _default: {
string: import("..").ExecuteValidator;
method: import("..").ExecuteValidator;
number: import("..").ExecuteValidator;
boolean: import("..").ExecuteValidator;
regexp: import("..").ExecuteValidator;
integer: import("..").ExecuteValidator;
float: import("..").ExecuteValidator;
array: import("..").ExecuteValidator;
object: import("..").ExecuteValidator;
enum: import("..").ExecuteValidator;
pattern: import("..").ExecuteValidator;
date: import("..").ExecuteValidator;
url: import("..").ExecuteValidator;
hex: import("..").ExecuteValidator;
email: import("..").ExecuteValidator;
required: import("..").ExecuteValidator;
any: import("..").ExecuteValidator;
};
export default _default;

View File

@@ -0,0 +1,34 @@
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,
required: required,
any: any
};

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const integer: ExecuteValidator;
export default integer;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const method: ExecuteValidator;
export default method;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const number: ExecuteValidator;
export default number;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const object: ExecuteValidator;
export default object;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const pattern: ExecuteValidator;
export default pattern;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const regexp: ExecuteValidator;
export default regexp;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const required: ExecuteValidator;
export default required;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const string: ExecuteValidator;
export default string;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const type: ExecuteValidator;
export default type;

View File

@@ -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;

View File

@@ -0,0 +1,43 @@
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;
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): import("./interface").ExecuteValidator | ((rule: InternalRuleItem, value: any, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | import("./interface").SyncValidateResult);
}
export default Schema;

310
node_modules/@rc-component/async-validator/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,310 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {};
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _messages2 = require("./messages");
var _util = require("./util");
var _index = _interopRequireDefault(require("./validator/index"));
var _interface = require("./interface");
Object.keys(_interface).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _interface[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _interface[key];
}
});
});
/**
* Encapsulates a validation schema.
*
* @param descriptor An object declaring validation rules
* for this schema.
*/
var Schema = /*#__PURE__*/function () {
function Schema(descriptor) {
(0, _classCallCheck2.default)(this, Schema);
// ======================== Instance ========================
(0, _defineProperty2.default)(this, "rules", null);
(0, _defineProperty2.default)(this, "_messages", _messages2.messages);
this.define(descriptor);
}
(0, _createClass2.default)(Schema, [{
key: "define",
value: function define(rules) {
var _this = this;
if (!rules) {
throw new Error('Cannot configure a schema with no rules');
}
if ((0, _typeof2.default)(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 = (0, _util.deepMerge)((0, _messages2.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, (0, _toConsumableArray2.default)(e));
} else {
errors.push(e);
}
}
for (var i = 0; i < results.length; i++) {
add(results[i]);
}
if (!errors.length) {
callback(null, source);
} else {
fields = (0, _util.convertFieldsError)(errors);
callback(errors, fields);
}
}
if (options.messages) {
var messages = this.messages();
if (messages === _messages2.messages) {
messages = (0, _messages2.newMessages)();
}
(0, _util.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 = (0, _objectSpread2.default)({}, source);
}
value = source[z] = rule.transform(value);
if (value !== undefined && value !== null) {
rule.type = rule.type || (Array.isArray(value) ? 'array' : (0, _typeof2.default)(value));
}
}
if (typeof rule === 'function') {
rule = {
validator: rule
};
} else {
rule = (0, _objectSpread2.default)({}, 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 (0, _util.asyncMap)(series, options, function (data, doIt) {
var rule = data.rule;
var deep = (rule.type === 'object' || rule.type === 'array') && ((0, _typeof2.default)(rule.fields) === 'object' || (0, _typeof2.default)(rule.defaultField) === 'object');
deep = deep && (rule.required || !rule.required && data.value);
rule.field = data.field;
function addFullField(key, schema) {
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, schema), {}, {
fullField: "".concat(rule.fullField, ".").concat(key),
fullFields: rule.fullFields ? [].concat((0, _toConsumableArray2.default)(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) {
errorList = [].concat(rule.message);
}
// Fill error info
var filledErrors = errorList.map((0, _util.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((0, _util.complementError)(rule, source));
} else if (options.error) {
filledErrors = [options.error(rule, (0, _util.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 = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, 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, (0, _toConsumableArray2.default)(filledErrors));
}
if (errs && errs.length) {
finalErrors.push.apply(finalErrors, (0, _toConsumableArray2.default)(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 && !_index.default.hasOwnProperty(rule.type)) {
throw new Error((0, _util.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 _index.default.required;
}
return _index.default[this.getType(rule)] || undefined;
}
}]);
return Schema;
}();
// ========================= Static =========================
(0, _defineProperty2.default)(Schema, "register", function register(type, validator) {
if (typeof validator !== 'function') {
throw new Error('Cannot register a validator by type, validator is not a function');
}
_index.default[type] = validator;
});
(0, _defineProperty2.default)(Schema, "warning", _util.warning);
(0, _defineProperty2.default)(Schema, "messages", _messages2.messages);
(0, _defineProperty2.default)(Schema, "validators", _index.default);
var _default = exports.default = Schema;

View File

@@ -0,0 +1,135 @@
export type RuleType = 'string' | 'number' | 'boolean' | 'method' | 'regexp' | 'integer' | 'float' | 'array' | 'object' | 'enum' | 'date' | 'url' | 'hex' | 'email' | '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]>;
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 {};

View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});

View File

@@ -0,0 +1,3 @@
import type { InternalValidateMessages } from './interface';
export declare function newMessages(): InternalValidateMessages;
export declare const messages: InternalValidateMessages;

View File

@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.messages = void 0;
exports.newMessages = newMessages;
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',
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;
}
};
}
var messages = exports.messages = newMessages();

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const enumerable: ExecuteRule;
export default enumerable;

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("../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((0, _util.format)(options.messages[ENUM], rule.fullField, rule[ENUM].join(', ')));
}
};
var _default = exports.default = enumerable;

View File

@@ -0,0 +1,9 @@
declare const _default: {
required: import("..").ExecuteRule;
whitespace: import("..").ExecuteRule;
type: import("..").ExecuteRule;
range: import("..").ExecuteRule;
enum: import("..").ExecuteRule;
pattern: import("..").ExecuteRule;
};
export default _default;

View File

@@ -0,0 +1,21 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _enum = _interopRequireDefault(require("./enum"));
var _pattern = _interopRequireDefault(require("./pattern"));
var _range = _interopRequireDefault(require("./range"));
var _required = _interopRequireDefault(require("./required"));
var _type = _interopRequireDefault(require("./type"));
var _whitespace = _interopRequireDefault(require("./whitespace"));
var _default = exports.default = {
required: _required.default,
whitespace: _whitespace.default,
type: _type.default,
range: _range.default,
enum: _enum.default,
pattern: _pattern.default
};

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const pattern: ExecuteRule;
export default pattern;

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("../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((0, _util.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((0, _util.format)(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
}
}
}
};
var _default = exports.default = pattern;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const range: ExecuteRule;
export default range;

View File

@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("../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((0, _util.format)(options.messages[key].len, rule.fullField, rule.len));
}
} else if (min && !max && val < rule.min) {
errors.push((0, _util.format)(options.messages[key].min, rule.fullField, rule.min));
} else if (max && !min && val > rule.max) {
errors.push((0, _util.format)(options.messages[key].max, rule.fullField, rule.max));
} else if (min && max && (val < rule.min || val > rule.max)) {
errors.push((0, _util.format)(options.messages[key].range, rule.fullField, rule.min, rule.max));
}
};
var _default = exports.default = range;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const required: ExecuteRule;
export default required;

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("../util");
var required = function required(rule, value, source, errors, options, type) {
if (rule.required && (!source.hasOwnProperty(rule.field) || (0, _util.isEmptyValue)(value, type || rule.type))) {
errors.push((0, _util.format)(options.messages.required, rule.fullField));
}
};
var _default = exports.default = required;

View File

@@ -0,0 +1,3 @@
import type { ExecuteRule } from '../interface';
declare const type: ExecuteRule;
export default type;

View File

@@ -0,0 +1,84 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _util = require("../util");
var _required = _interopRequireDefault(require("./required"));
var _url = _interopRequireDefault(require("./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',
// ),
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 (0, _typeof2.default)(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);
},
url: function url(value) {
return typeof value === 'string' && value.length <= 2048 && !!value.match((0, _url.default)());
},
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) {
(0, _required.default)(rule, value, source, errors, options);
return;
}
var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex'];
var ruleType = rule.type;
if (custom.indexOf(ruleType) > -1) {
if (!types[ruleType](value)) {
errors.push((0, _util.format)(options.messages.types[ruleType], rule.fullField, rule.type));
}
// straight typeof check
} else if (ruleType && (0, _typeof2.default)(value) !== rule.type) {
errors.push((0, _util.format)(options.messages.types[ruleType], rule.fullField, rule.type));
}
};
var _default = exports.default = type;

View File

@@ -0,0 +1,2 @@
declare const _default: () => RegExp;
export default _default;

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
// https://github.com/kevva/url-regex/blob/master/index.js
var urlReg;
var _default = exports.default = function _default() {
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;
};

View File

@@ -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;

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _util = require("../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((0, _util.format)(options.messages.whitespace, rule.fullField));
}
};
var _default = exports.default = whitespace;

View File

@@ -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 {};

259
node_modules/@rc-component/async-validator/lib/util.js generated vendored Normal file
View File

@@ -0,0 +1,259 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AsyncValidationError = void 0;
exports.asyncMap = asyncMap;
exports.complementError = complementError;
exports.convertFieldsError = convertFieldsError;
exports.deepMerge = deepMerge;
exports.format = format;
exports.isEmptyObject = isEmptyObject;
exports.isEmptyValue = isEmptyValue;
exports.warning = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));
var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
/* eslint no-console:0 */
var formatRegExp = /%[sdj%]/g;
var warning = exports.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') {
exports.warning = 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);
}
}
};
}
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;
}
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';
}
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;
}
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, (0, _toConsumableArray2.default)(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, (0, _toConsumableArray2.default)(objArr[k] || []));
});
return ret;
}
var AsyncValidationError = exports.AsyncValidationError = /*#__PURE__*/function (_Error) {
(0, _inherits2.default)(AsyncValidationError, _Error);
var _super = (0, _createSuper2.default)(AsyncValidationError);
function AsyncValidationError(errors, fields) {
var _this;
(0, _classCallCheck2.default)(this, AsyncValidationError);
_this = _super.call(this, 'Async Validation Error');
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "errors", void 0);
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "fields", void 0);
_this.errors = errors;
_this.fields = fields;
return _this;
}
return (0, _createClass2.default)(AsyncValidationError);
}( /*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
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;
}
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
};
};
}
function deepMerge(target, source) {
if (source) {
for (var s in source) {
if (source.hasOwnProperty(s)) {
var value = source[s];
if ((0, _typeof2.default)(value) === 'object' && (0, _typeof2.default)(target[s]) === 'object') {
target[s] = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, target[s]), value);
} else {
target[s] = value;
}
}
}
}
return target;
}

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const any: ExecuteValidator;
export default any;

View File

@@ -0,0 +1,21 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
}
callback(errors);
};
var _default = exports.default = any;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const array: ExecuteValidator;
export default array;

View File

@@ -0,0 +1,24 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _index = _interopRequireDefault(require("../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();
}
_index.default.required(rule, value, source, errors, options, 'array');
if (value !== undefined && value !== null) {
_index.default.type(rule, value, source, errors, options);
_index.default.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = array;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const boolean: ExecuteValidator;
export default boolean;

View File

@@ -0,0 +1,24 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (value !== undefined) {
_rule.default.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = boolean;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const date: ExecuteValidator;
export default date;

View File

@@ -0,0 +1,35 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value, 'date') && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (!(0, _util.isEmptyValue)(value, 'date')) {
var dateObject;
if (value instanceof Date) {
dateObject = value;
} else {
dateObject = new Date(value);
}
_rule.default.type(rule, dateObject, source, errors, options);
if (dateObject) {
_rule.default.range(rule, dateObject.getTime(), source, errors, options);
}
}
}
callback(errors);
};
var _default = exports.default = date;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const enumerable: ExecuteValidator;
export default enumerable;

View File

@@ -0,0 +1,25 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (value !== undefined) {
_rule.default[ENUM](rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = enumerable;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const floatFn: ExecuteValidator;
export default floatFn;

View File

@@ -0,0 +1,25 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (value !== undefined) {
_rule.default.type(rule, value, source, errors, options);
_rule.default.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = floatFn;

View File

@@ -0,0 +1,20 @@
declare const _default: {
string: import("..").ExecuteValidator;
method: import("..").ExecuteValidator;
number: import("..").ExecuteValidator;
boolean: import("..").ExecuteValidator;
regexp: import("..").ExecuteValidator;
integer: import("..").ExecuteValidator;
float: import("..").ExecuteValidator;
array: import("..").ExecuteValidator;
object: import("..").ExecuteValidator;
enum: import("..").ExecuteValidator;
pattern: import("..").ExecuteValidator;
date: import("..").ExecuteValidator;
url: import("..").ExecuteValidator;
hex: import("..").ExecuteValidator;
email: import("..").ExecuteValidator;
required: import("..").ExecuteValidator;
any: import("..").ExecuteValidator;
};
export default _default;

View File

@@ -0,0 +1,41 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _any = _interopRequireDefault(require("./any"));
var _array = _interopRequireDefault(require("./array"));
var _boolean = _interopRequireDefault(require("./boolean"));
var _date = _interopRequireDefault(require("./date"));
var _enum = _interopRequireDefault(require("./enum"));
var _float = _interopRequireDefault(require("./float"));
var _integer = _interopRequireDefault(require("./integer"));
var _method = _interopRequireDefault(require("./method"));
var _number = _interopRequireDefault(require("./number"));
var _object = _interopRequireDefault(require("./object"));
var _pattern = _interopRequireDefault(require("./pattern"));
var _regexp = _interopRequireDefault(require("./regexp"));
var _required = _interopRequireDefault(require("./required"));
var _string = _interopRequireDefault(require("./string"));
var _type = _interopRequireDefault(require("./type"));
var _default = exports.default = {
string: _string.default,
method: _method.default,
number: _number.default,
boolean: _boolean.default,
regexp: _regexp.default,
integer: _integer.default,
float: _float.default,
array: _array.default,
object: _object.default,
enum: _enum.default,
pattern: _pattern.default,
date: _date.default,
url: _type.default,
hex: _type.default,
email: _type.default,
required: _required.default,
any: _any.default
};

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const integer: ExecuteValidator;
export default integer;

View File

@@ -0,0 +1,25 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (value !== undefined) {
_rule.default.type(rule, value, source, errors, options);
_rule.default.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = integer;

View File

@@ -0,0 +1,3 @@
import type { ExecuteValidator } from '../interface';
declare const method: ExecuteValidator;
export default method;

View File

@@ -0,0 +1,24 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rule = _interopRequireDefault(require("../rule"));
var _util = require("../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 ((0, _util.isEmptyValue)(value) && !rule.required) {
return callback();
}
_rule.default.required(rule, value, source, errors, options);
if (value !== undefined) {
_rule.default.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var _default = exports.default = method;

Some files were not shown because too many files have changed in this diff Show More