@astral/validations 2.26.0 → 3.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +1243 -1
- package/any/any.d.ts +21 -0
- package/any/any.js +14 -0
- package/any/index.d.ts +1 -0
- package/any/index.js +1 -0
- package/array/array.d.ts +15 -0
- package/array/array.js +21 -0
- package/array/constants.d.ts +2 -0
- package/array/constants.js +5 -0
- package/array/index.d.ts +2 -0
- package/array/index.js +2 -0
- package/arrayItem/arrayItem.d.ts +35 -0
- package/arrayItem/arrayItem.js +33 -0
- package/arrayItem/index.d.ts +1 -0
- package/arrayItem/index.js +1 -0
- package/boolean/boolean.d.ts +13 -0
- package/boolean/boolean.js +19 -0
- package/boolean/constants.d.ts +2 -0
- package/boolean/constants.js +5 -0
- package/boolean/index.d.ts +2 -0
- package/boolean/index.js +2 -0
- package/core/compose/compose.d.ts +6 -0
- package/{compose → core/compose}/compose.js +2 -3
- package/core/context/createContext/createContext.d.ts +8 -0
- package/core/context/createContext/createContext.js +15 -0
- package/core/context/createContext/index.d.ts +1 -0
- package/core/context/createContext/index.js +1 -0
- package/core/context/index.d.ts +2 -0
- package/core/context/index.js +2 -0
- package/core/context/types.d.ts +28 -0
- package/core/errors/ArrayError/ArrayError.d.ts +18 -0
- package/core/errors/ArrayError/ArrayError.js +10 -0
- package/core/errors/ArrayError/createArrayError/createArrayError.d.ts +5 -0
- package/core/errors/ArrayError/createArrayError/createArrayError.js +11 -0
- package/core/errors/ArrayError/createArrayError/index.d.ts +1 -0
- package/core/errors/ArrayError/createArrayError/index.js +1 -0
- package/core/errors/ArrayError/index.d.ts +2 -0
- package/core/errors/ArrayError/index.js +2 -0
- package/core/errors/ErrorMap/ErrorMap.d.ts +21 -0
- package/core/errors/ErrorMap/ErrorMap.js +10 -0
- package/core/errors/ErrorMap/createErrorMap/createErrorMap.d.ts +5 -0
- package/core/errors/ErrorMap/createErrorMap/createErrorMap.js +10 -0
- package/core/errors/ErrorMap/createErrorMap/index.d.ts +1 -0
- package/core/errors/ErrorMap/createErrorMap/index.js +1 -0
- package/core/errors/ErrorMap/index.d.ts +2 -0
- package/core/errors/ErrorMap/index.js +2 -0
- package/core/errors/SimpleError/SimpleError.d.ts +16 -0
- package/core/errors/SimpleError/SimpleError.js +9 -0
- package/core/errors/SimpleError/createSimpleError/createSimpleError.d.ts +6 -0
- package/core/errors/SimpleError/createSimpleError/createSimpleError.js +5 -0
- package/core/errors/SimpleError/createSimpleError/index.d.ts +1 -0
- package/core/errors/SimpleError/createSimpleError/index.js +1 -0
- package/core/errors/SimpleError/index.d.ts +2 -0
- package/core/errors/SimpleError/index.js +2 -0
- package/core/errors/createErrorCode/createErrorCode.d.ts +5 -0
- package/core/errors/createErrorCode/createErrorCode.js +4 -0
- package/core/errors/createErrorCode/index.d.ts +1 -0
- package/core/errors/createErrorCode/index.js +1 -0
- package/core/errors/index.d.ts +5 -0
- package/core/errors/index.js +5 -0
- package/core/errors/types.d.ts +18 -0
- package/core/errors/types.js +1 -0
- package/core/guard/createGuard/createGuard.d.ts +54 -0
- package/core/guard/createGuard/createGuard.js +41 -0
- package/core/guard/createGuard/index.d.ts +1 -0
- package/core/guard/createGuard/index.js +1 -0
- package/core/guard/index.d.ts +1 -0
- package/core/guard/index.js +1 -0
- package/core/index.d.ts +8 -0
- package/core/index.js +8 -0
- package/core/rule/createRule/createRule.d.ts +42 -0
- package/core/rule/createRule/createRule.js +27 -0
- package/core/rule/index.d.ts +3 -0
- package/core/rule/index.js +3 -0
- package/core/rule/required/constants.d.ts +2 -0
- package/core/rule/required/constants.js +5 -0
- package/core/rule/required/index.d.ts +2 -0
- package/core/rule/required/index.js +2 -0
- package/core/rule/required/required.d.ts +19 -0
- package/core/rule/required/required.js +25 -0
- package/core/rule/types.d.ts +15 -0
- package/core/rule/types.js +1 -0
- package/core/types.d.ts +9 -0
- package/core/types.js +1 -0
- package/{utils → core/utils}/index.d.ts +1 -1
- package/{utils → core/utils}/index.js +1 -1
- package/core/utils/isStringOfZeros/index.d.ts +1 -0
- package/core/utils/isStringOfZeros/index.js +1 -0
- package/{utils → core/utils/isStringOfZeros}/isStringOfZeros.d.ts +1 -1
- package/{utils → core/utils/isStringOfZeros}/isStringOfZeros.js +1 -1
- package/core/utils/resetTime/index.d.ts +1 -0
- package/core/utils/resetTime/index.js +1 -0
- package/core/utils/resetTime/resetTime.d.ts +5 -0
- package/core/utils/resetTime/resetTime.js +12 -0
- package/date/constants.d.ts +3 -0
- package/date/constants.js +9 -0
- package/date/date.d.ts +19 -0
- package/date/date.js +24 -0
- package/date/index.d.ts +1 -0
- package/date/index.js +1 -0
- package/deepPartial/deepPartial.d.ts +29 -0
- package/deepPartial/deepPartial.js +21 -0
- package/deepPartial/index.d.ts +1 -0
- package/deepPartial/index.js +1 -0
- package/email/constants.d.ts +5 -0
- package/email/constants.js +11 -0
- package/email/email.d.ts +28 -0
- package/email/email.js +19 -0
- package/email/index.d.ts +2 -0
- package/email/index.js +2 -0
- package/index.d.ts +24 -20
- package/index.js +24 -20
- package/innIP/constants.d.ts +5 -0
- package/innIP/constants.js +8 -0
- package/innIP/index.d.ts +2 -0
- package/innIP/index.js +2 -0
- package/innIP/innIP.d.ts +25 -0
- package/innIP/innIP.js +40 -0
- package/innUL/constants.d.ts +4 -0
- package/innUL/constants.js +7 -0
- package/innUL/index.d.ts +2 -0
- package/innUL/index.js +2 -0
- package/innUL/innUL.d.ts +25 -0
- package/innUL/innUL.js +36 -0
- package/kpp/constants.d.ts +3 -0
- package/kpp/constants.js +6 -0
- package/kpp/index.d.ts +2 -0
- package/kpp/index.js +2 -0
- package/kpp/kpp.d.ts +25 -0
- package/kpp/kpp.js +16 -0
- package/max/constants.d.ts +5 -0
- package/max/constants.js +5 -0
- package/max/index.d.ts +2 -0
- package/max/index.js +2 -0
- package/max/max.d.ts +26 -0
- package/max/max.js +42 -0
- package/min/constants.d.ts +5 -0
- package/min/constants.js +5 -0
- package/min/index.d.ts +2 -0
- package/min/index.js +2 -0
- package/min/min.d.ts +26 -0
- package/min/min.js +42 -0
- package/mobilePhone/constants.d.ts +3 -0
- package/mobilePhone/constants.js +6 -0
- package/mobilePhone/index.d.ts +2 -0
- package/mobilePhone/index.js +2 -0
- package/mobilePhone/mobilePhone.d.ts +27 -0
- package/mobilePhone/mobilePhone.js +21 -0
- package/number/constants.d.ts +4 -0
- package/number/constants.js +13 -0
- package/number/index.d.ts +2 -0
- package/number/index.js +2 -0
- package/number/number.d.ts +19 -0
- package/number/number.js +26 -0
- package/object/constants.d.ts +2 -0
- package/object/constants.js +5 -0
- package/object/index.d.ts +2 -0
- package/object/index.js +2 -0
- package/object/isEmptyErrors/index.d.ts +1 -0
- package/object/isEmptyErrors/index.js +1 -0
- package/object/isEmptyErrors/isEmptyErrors.d.ts +5 -0
- package/object/isEmptyErrors/isEmptyErrors.js +4 -0
- package/object/object.d.ts +52 -0
- package/object/object.js +50 -0
- package/ogrnIP/constants.d.ts +3 -0
- package/ogrnIP/constants.js +6 -0
- package/ogrnIP/index.d.ts +2 -0
- package/ogrnIP/index.js +2 -0
- package/ogrnIP/ogrnIP.d.ts +25 -0
- package/ogrnIP/ogrnIP.js +27 -0
- package/ogrnUL/constants.d.ts +3 -0
- package/ogrnUL/constants.js +6 -0
- package/ogrnUL/index.d.ts +2 -0
- package/ogrnUL/index.js +2 -0
- package/ogrnUL/ogrnUL.d.ts +25 -0
- package/ogrnUL/ogrnUL.js +27 -0
- package/onlyNumber/constants.d.ts +2 -0
- package/onlyNumber/constants.js +2 -0
- package/onlyNumber/index.d.ts +2 -0
- package/onlyNumber/index.js +2 -0
- package/onlyNumber/onlyNumber.d.ts +24 -0
- package/onlyNumber/onlyNumber.js +20 -0
- package/optional/index.d.ts +1 -0
- package/optional/index.js +1 -0
- package/optional/optional.d.ts +7 -0
- package/optional/optional.js +15 -0
- package/or/index.d.ts +1 -0
- package/or/index.js +1 -0
- package/or/or.d.ts +22 -0
- package/or/or.js +21 -0
- package/package.json +2 -2
- package/partial/index.d.ts +1 -0
- package/partial/index.js +1 -0
- package/partial/partial.d.ts +10 -0
- package/partial/partial.js +6 -0
- package/pattern/constants.d.ts +2 -0
- package/pattern/constants.js +2 -0
- package/pattern/index.d.ts +2 -0
- package/pattern/index.js +2 -0
- package/pattern/pattern.d.ts +26 -0
- package/pattern/pattern.js +22 -0
- package/snils/constants.d.ts +4 -0
- package/snils/constants.js +7 -0
- package/snils/index.d.ts +2 -0
- package/snils/index.js +2 -0
- package/snils/snils.d.ts +25 -0
- package/{isSNILS/isSNILS.js → snils/snils.js} +20 -21
- package/string/constants.d.ts +2 -0
- package/string/constants.js +5 -0
- package/string/index.d.ts +2 -0
- package/string/index.js +2 -0
- package/string/string.d.ts +2 -0
- package/string/string.js +8 -0
- package/toPlainError/index.d.ts +1 -0
- package/toPlainError/index.js +1 -0
- package/toPlainError/toPlainError.d.ts +35 -0
- package/toPlainError/toPlainError.js +49 -0
- package/toPlainError/utils/generateArrayPath/generateArrayPath.d.ts +4 -0
- package/toPlainError/utils/generateArrayPath/generateArrayPath.js +9 -0
- package/toPlainError/utils/generateArrayPath/index.d.ts +1 -0
- package/toPlainError/utils/generateArrayPath/index.js +1 -0
- package/toPlainError/utils/generateObjectPath/generateObjectPath.d.ts +4 -0
- package/toPlainError/utils/generateObjectPath/generateObjectPath.js +9 -0
- package/toPlainError/utils/generateObjectPath/index.d.ts +1 -0
- package/toPlainError/utils/generateObjectPath/index.js +1 -0
- package/toPlainError/utils/index.d.ts +2 -0
- package/toPlainError/utils/index.js +2 -0
- package/transform/index.d.ts +1 -0
- package/transform/index.js +1 -0
- package/transform/transform.d.ts +26 -0
- package/transform/transform.js +16 -0
- package/when/index.d.ts +1 -0
- package/when/index.js +1 -0
- package/when/when.d.ts +47 -0
- package/when/when.js +29 -0
- package/compose/compose.d.ts +0 -7
- package/composeSome/composeSome.d.ts +0 -8
- package/composeSome/composeSome.js +0 -25
- package/composeSome/index.d.ts +0 -1
- package/composeSome/index.js +0 -1
- package/constants.d.ts +0 -2
- package/constants.js +0 -2
- package/createRule/createRule.d.ts +0 -14
- package/createRule/createRule.js +0 -12
- package/isDate/index.d.ts +0 -1
- package/isDate/index.js +0 -1
- package/isDate/isDate.d.ts +0 -10
- package/isDate/isDate.js +0 -23
- package/isEmail/index.d.ts +0 -1
- package/isEmail/index.js +0 -1
- package/isEmail/isEmail.d.ts +0 -13
- package/isEmail/isEmail.js +0 -25
- package/isINNIP/index.d.ts +0 -1
- package/isINNIP/index.js +0 -1
- package/isINNIP/isINNIP.d.ts +0 -10
- package/isINNIP/isINNIP.js +0 -42
- package/isINNUL/index.d.ts +0 -1
- package/isINNUL/index.js +0 -1
- package/isINNUL/isINNUL.d.ts +0 -10
- package/isINNUL/isINNUL.js +0 -37
- package/isKPP/index.d.ts +0 -1
- package/isKPP/index.js +0 -1
- package/isKPP/isKPP.d.ts +0 -7
- package/isKPP/isKPP.js +0 -19
- package/isMaxLength/index.d.ts +0 -1
- package/isMaxLength/index.js +0 -1
- package/isMaxLength/isMaxLength.d.ts +0 -18
- package/isMaxLength/isMaxLength.js +0 -34
- package/isMaxValue/index.d.ts +0 -1
- package/isMaxValue/index.js +0 -1
- package/isMaxValue/isMaxValue.d.ts +0 -17
- package/isMaxValue/isMaxValue.js +0 -35
- package/isMaybeNumber/index.d.ts +0 -1
- package/isMaybeNumber/index.js +0 -1
- package/isMaybeNumber/isMaybeNumber.d.ts +0 -10
- package/isMaybeNumber/isMaybeNumber.js +0 -23
- package/isMinLength/index.d.ts +0 -1
- package/isMinLength/index.js +0 -1
- package/isMinLength/isMinLength.d.ts +0 -18
- package/isMinLength/isMinLength.js +0 -34
- package/isMinValue/index.d.ts +0 -1
- package/isMinValue/index.js +0 -1
- package/isMinValue/isMinValue.d.ts +0 -17
- package/isMinValue/isMinValue.js +0 -35
- package/isMobilePhone/index.d.ts +0 -1
- package/isMobilePhone/index.js +0 -1
- package/isMobilePhone/isMobilePhone.d.ts +0 -10
- package/isMobilePhone/isMobilePhone.js +0 -20
- package/isOGRNIP/index.d.ts +0 -1
- package/isOGRNIP/index.js +0 -1
- package/isOGRNIP/isOGRNIP.d.ts +0 -10
- package/isOGRNIP/isOGRNIP.js +0 -29
- package/isOGRNUL/index.d.ts +0 -1
- package/isOGRNUL/index.js +0 -1
- package/isOGRNUL/isOGRNUL.d.ts +0 -10
- package/isOGRNUL/isOGRNUL.js +0 -29
- package/isRequired/index.d.ts +0 -1
- package/isRequired/index.js +0 -1
- package/isRequired/isRequired.d.ts +0 -11
- package/isRequired/isRequired.js +0 -23
- package/isSNILS/index.d.ts +0 -1
- package/isSNILS/index.js +0 -1
- package/isSNILS/isSNILS.d.ts +0 -10
- package/types.d.ts +0 -4
- package/utils/isEmptyString.d.ts +0 -4
- package/utils/isEmptyString.js +0 -6
- package/yupAdapter/index.d.ts +0 -1
- package/yupAdapter/index.js +0 -1
- package/yupAdapter/yupAdapter.d.ts +0 -8
- package/yupAdapter/yupAdapter.js +0 -11
- /package/{compose → core/compose}/index.d.ts +0 -0
- /package/{compose → core/compose}/index.js +0 -0
- /package/{types.js → core/context/types.js} +0 -0
- /package/{createRule → core/rule/createRule}/index.d.ts +0 -0
- /package/{createRule → core/rule/createRule}/index.js +0 -0
@@ -0,0 +1,41 @@
|
|
1
|
+
import { REQUIRED_ERROR_INFO, required } from '../../rule';
|
2
|
+
import { createContext } from '../../context';
|
3
|
+
import { compose } from '../../compose';
|
4
|
+
/**
|
5
|
+
* @description Создает guard. Guard - функция, проверяющая тип значения
|
6
|
+
* По-дефолту проверяет value на required. Для выключения required необходимо использовать optional().
|
7
|
+
* После первого вызова guard в прототипу функции становится доступен метод define, который позволяет переопределить дефолтное поведение guard (например, изменить текст для required правила)
|
8
|
+
* @example
|
9
|
+
* ```ts
|
10
|
+
* const string = <TValues>(...rules: ValidationRule<string, TValues>[]) =>
|
11
|
+
* createGuard<string, TValues>((value, ctx) => {
|
12
|
+
* if (typeof value !== 'string') {
|
13
|
+
* return ctx.createError({ code: 'custom error', message: 'Не строка' });
|
14
|
+
* }
|
15
|
+
*
|
16
|
+
* return compose<string, TValues>(...rules)(value, ctx);
|
17
|
+
* });
|
18
|
+
* ```
|
19
|
+
*/
|
20
|
+
export const createGuard = (executeGuard) => {
|
21
|
+
// выделено в отдельную именованную функцию для того, чтобы ее можно было рекурсивно вызывать в define
|
22
|
+
const createInnerGuard = (defOptions = {}) => {
|
23
|
+
const guard = (value, prevCtx) => {
|
24
|
+
const ctx = createContext(prevCtx,
|
25
|
+
// при создании контекста сейчас не имеет значение какого типа будет ctx.values
|
26
|
+
value);
|
27
|
+
const validationResult = compose(
|
28
|
+
// возможность переопределить дефолтный message для required
|
29
|
+
required({ message: defOptions === null || defOptions === void 0 ? void 0 : defOptions.requiredErrorMessage }), (interValue, interCtx) => executeGuard(interValue, interCtx, defOptions))(value, ctx);
|
30
|
+
// если включен isOptional режим и required упал с ошибкой, то необходимо проигнорировать ошибку
|
31
|
+
if ((defOptions === null || defOptions === void 0 ? void 0 : defOptions.isOptional) &&
|
32
|
+
(validationResult === null || validationResult === void 0 ? void 0 : validationResult.cause.code) === REQUIRED_ERROR_INFO.code) {
|
33
|
+
return undefined;
|
34
|
+
}
|
35
|
+
return validationResult;
|
36
|
+
};
|
37
|
+
guard.define = (overridesDefOptions) => createInnerGuard(overridesDefOptions);
|
38
|
+
return guard;
|
39
|
+
};
|
40
|
+
return createInnerGuard();
|
41
|
+
};
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './createGuard';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './createGuard';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './createGuard';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './createGuard';
|
package/core/index.d.ts
ADDED
package/core/index.js
ADDED
@@ -0,0 +1,42 @@
|
|
1
|
+
import { ValidationResult, ValidationTypes } from '../../types';
|
2
|
+
import { ValidationContext } from '../../context';
|
3
|
+
import { IndependentValidationRule } from '../types';
|
4
|
+
/**
|
5
|
+
* @description Единые параметры для всех правил
|
6
|
+
*/
|
7
|
+
export type CommonRuleParams<ValidationType extends ValidationTypes> = {
|
8
|
+
/**
|
9
|
+
* @description Функция, позволяющая для каждого правила указать исключение
|
10
|
+
*/
|
11
|
+
exclude?: (value: ValidationType, ctx: ValidationContext<unknown>) => boolean;
|
12
|
+
};
|
13
|
+
/**
|
14
|
+
* @description Функция, которая позволяет определять частную логику для guard
|
15
|
+
*/
|
16
|
+
type RuleExecutor<ValidationType extends ValidationTypes, TValues> = (value: ValidationType, ctx: ValidationContext<TValues>) => ValidationResult;
|
17
|
+
/**
|
18
|
+
* @description Создает правила валидации, которые можно использовать внутри guard или по отдельности
|
19
|
+
* @param executor - функция, которая позволяет определять частную логику для guard
|
20
|
+
* @param commonParams - единые параметры для всех rule
|
21
|
+
* @example
|
22
|
+
* ```ts
|
23
|
+
* const inn = (params: CommonRuleParams<string> & { message?: string }) =>
|
24
|
+
* createRule<string>((value, ctx) => {
|
25
|
+
* if (!isInn(value)) {
|
26
|
+
* return ctx.createError({ code: 'custom error', message: params?.message || 'Неверный ИНН' });
|
27
|
+
* }
|
28
|
+
*
|
29
|
+
* return undefined;
|
30
|
+
* }, params);
|
31
|
+
* ```
|
32
|
+
*/
|
33
|
+
export declare const createRule: <ValidationType extends unknown, TValues = unknown>(executor: RuleExecutor<ValidationType, TValues>, commonParams?: CommonRuleParams<ValidationType> | undefined) => (value: ValidationType, prevCtx?: Readonly<{
|
34
|
+
global: Readonly<{
|
35
|
+
values: TValues;
|
36
|
+
overrides: Readonly<{
|
37
|
+
objectIsPartial: boolean;
|
38
|
+
}>;
|
39
|
+
}>;
|
40
|
+
createError: ({ message, code }: import("../..").ErrorInfo) => import("../..").ValidationSimpleError<{}>;
|
41
|
+
}> | undefined) => ValidationResult;
|
42
|
+
export {};
|
@@ -0,0 +1,27 @@
|
|
1
|
+
import { createContext } from '../../context';
|
2
|
+
/**
|
3
|
+
* @description Создает правила валидации, которые можно использовать внутри guard или по отдельности
|
4
|
+
* @param executor - функция, которая позволяет определять частную логику для guard
|
5
|
+
* @param commonParams - единые параметры для всех rule
|
6
|
+
* @example
|
7
|
+
* ```ts
|
8
|
+
* const inn = (params: CommonRuleParams<string> & { message?: string }) =>
|
9
|
+
* createRule<string>((value, ctx) => {
|
10
|
+
* if (!isInn(value)) {
|
11
|
+
* return ctx.createError({ code: 'custom error', message: params?.message || 'Неверный ИНН' });
|
12
|
+
* }
|
13
|
+
*
|
14
|
+
* return undefined;
|
15
|
+
* }, params);
|
16
|
+
* ```
|
17
|
+
*/
|
18
|
+
export const createRule = (executor, commonParams) => (value, prevCtx) => {
|
19
|
+
var _a;
|
20
|
+
// контекст создается, если он не был создан раннее
|
21
|
+
const ctx = createContext(prevCtx, value);
|
22
|
+
// если value попало под исключения из правил, то дальше валидацию не продолжаем
|
23
|
+
if ((_a = commonParams === null || commonParams === void 0 ? void 0 : commonParams.exclude) === null || _a === void 0 ? void 0 : _a.call(commonParams, value, ctx)) {
|
24
|
+
return undefined;
|
25
|
+
}
|
26
|
+
return executor(value, ctx);
|
27
|
+
};
|
@@ -0,0 +1,19 @@
|
|
1
|
+
/**
|
2
|
+
* @description Проверяет value на пустоту. Если значение пустое, то возвращает ошибку.
|
3
|
+
* Правило универсально для всех типов данных
|
4
|
+
*/
|
5
|
+
export declare const required: ({ message, }?: {
|
6
|
+
/**
|
7
|
+
* @description Кастомное сообщение ошибки
|
8
|
+
* @default Обязательно
|
9
|
+
*/
|
10
|
+
message?: string | undefined;
|
11
|
+
}) => (value: unknown, prevCtx?: Readonly<{
|
12
|
+
global: Readonly<{
|
13
|
+
values: unknown;
|
14
|
+
overrides: Readonly<{
|
15
|
+
objectIsPartial: boolean;
|
16
|
+
}>;
|
17
|
+
}>;
|
18
|
+
createError: ({ message, code }: import("../..").ErrorInfo) => import("../..").ValidationSimpleError<{}>;
|
19
|
+
}> | undefined) => import("../..").ValidationResult;
|
@@ -0,0 +1,25 @@
|
|
1
|
+
import { createRule } from '../createRule';
|
2
|
+
import { REQUIRED_ERROR_INFO } from './constants';
|
3
|
+
/**
|
4
|
+
* @description Проверяет value на пустоту. Если значение пустое, то возвращает ошибку.
|
5
|
+
* Правило универсально для всех типов данных
|
6
|
+
*/
|
7
|
+
export const required = ({ message, } = {}) => createRule((value, ctx) => {
|
8
|
+
const createRequiredError = () => ctx.createError(Object.assign(Object.assign({}, REQUIRED_ERROR_INFO), { message: message || REQUIRED_ERROR_INFO.message }));
|
9
|
+
if (value === null) {
|
10
|
+
return createRequiredError();
|
11
|
+
}
|
12
|
+
if (typeof value === 'object') {
|
13
|
+
return undefined;
|
14
|
+
}
|
15
|
+
if (typeof value === 'number' || typeof value === 'symbol') {
|
16
|
+
return undefined;
|
17
|
+
}
|
18
|
+
if (typeof value === 'string') {
|
19
|
+
return value.trim() ? undefined : createRequiredError();
|
20
|
+
}
|
21
|
+
if (typeof value === 'boolean') {
|
22
|
+
return value ? undefined : createRequiredError();
|
23
|
+
}
|
24
|
+
return createRequiredError();
|
25
|
+
});
|
@@ -0,0 +1,15 @@
|
|
1
|
+
import { ValidationContext } from '../context';
|
2
|
+
import { ValidationResult } from '../types';
|
3
|
+
/**
|
4
|
+
* @description Самостоятельное правило для валидации. Может использоваться вне guard'ов
|
5
|
+
*/
|
6
|
+
export type IndependentValidationRule<TValue, TValues> = (value: TValue, ctx?: ValidationContext<TValues>) => ValidationResult;
|
7
|
+
/**
|
8
|
+
* @description Правило для валидации, работающее исключительно с guard'ами
|
9
|
+
*/
|
10
|
+
export type ValidationRule<TValue, TValues> = (value: TValue, ctx: ValidationContext<TValues>) => ValidationResult;
|
11
|
+
/**
|
12
|
+
* @description Композиционное правило валидации, умеющее работать с любыми значениями.
|
13
|
+
* В основном используется для композиционных правил, которые принимают rule, умеющие валидировать разные значения (optional, transform...)
|
14
|
+
*/
|
15
|
+
export type UniversalCompositionalValidationRule<TValues = unknown> = ValidationRule<any, TValues>;
|
@@ -0,0 +1 @@
|
|
1
|
+
export {};
|
package/core/types.d.ts
ADDED
@@ -0,0 +1,9 @@
|
|
1
|
+
import { ValidationError } from './errors';
|
2
|
+
/**
|
3
|
+
* @description Результат работы валидации
|
4
|
+
*/
|
5
|
+
export type ValidationResult = ValidationError | undefined;
|
6
|
+
/**
|
7
|
+
* @description Доступные для валидации типы value
|
8
|
+
*/
|
9
|
+
export type ValidationTypes = unknown | object | string | number | Date | Array<unknown>;
|
package/core/types.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
export {};
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './isStringOfZeros';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './isStringOfZeros';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './resetTime';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './resetTime';
|
@@ -0,0 +1,12 @@
|
|
1
|
+
/**
|
2
|
+
* @description Сбрасывает время для даты в 0
|
3
|
+
* @param date
|
4
|
+
*/
|
5
|
+
export const resetTime = (date) => {
|
6
|
+
const copyDate = new Date(date);
|
7
|
+
copyDate.setHours(0);
|
8
|
+
copyDate.setMinutes(0);
|
9
|
+
copyDate.setSeconds(0);
|
10
|
+
copyDate.setMilliseconds(0);
|
11
|
+
return copyDate;
|
12
|
+
};
|
@@ -0,0 +1,9 @@
|
|
1
|
+
import { createErrorCode } from '../core';
|
2
|
+
export const DATE_TYPE_ERROR_INFO = {
|
3
|
+
code: createErrorCode('date-type'),
|
4
|
+
message: 'Не дата',
|
5
|
+
};
|
6
|
+
export const INVALID_DATE_ERROR_INFO = {
|
7
|
+
code: createErrorCode('invalid-date'),
|
8
|
+
message: 'Некорректная дата',
|
9
|
+
};
|
package/date/date.d.ts
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
import { ValidationRule } from '../core';
|
2
|
+
type AdditionalDefOptions = {
|
3
|
+
invalidDateErrorMessage?: string;
|
4
|
+
};
|
5
|
+
/**
|
6
|
+
* @description Guard для Date object. Проверяет значение на соответствие объекту Date и на валидность даты
|
7
|
+
* @param rules - правила, валидирующие Date или unknown value
|
8
|
+
* @example
|
9
|
+
* ```ts
|
10
|
+
* const validate = date();
|
11
|
+
*
|
12
|
+
* // undefined
|
13
|
+
* validate(new Date());
|
14
|
+
* // invalid date error
|
15
|
+
* validate(new Date('22.22.2022'));
|
16
|
+
* ```
|
17
|
+
*/
|
18
|
+
export declare const date: <TValues>(...rules: ValidationRule<Date, TValues>[]) => import("../core").Guard<Date, TValues, AdditionalDefOptions>;
|
19
|
+
export {};
|
package/date/date.js
ADDED
@@ -0,0 +1,24 @@
|
|
1
|
+
import { compose, createGuard } from '../core';
|
2
|
+
import { DATE_TYPE_ERROR_INFO, INVALID_DATE_ERROR_INFO } from './constants';
|
3
|
+
/**
|
4
|
+
* @description Guard для Date object. Проверяет значение на соответствие объекту Date и на валидность даты
|
5
|
+
* @param rules - правила, валидирующие Date или unknown value
|
6
|
+
* @example
|
7
|
+
* ```ts
|
8
|
+
* const validate = date();
|
9
|
+
*
|
10
|
+
* // undefined
|
11
|
+
* validate(new Date());
|
12
|
+
* // invalid date error
|
13
|
+
* validate(new Date('22.22.2022'));
|
14
|
+
* ```
|
15
|
+
*/
|
16
|
+
export const date = (...rules) => createGuard((value, ctx, { typeErrorMessage, invalidDateErrorMessage }) => {
|
17
|
+
if (!(value instanceof Date)) {
|
18
|
+
return ctx.createError(Object.assign(Object.assign({}, DATE_TYPE_ERROR_INFO), { message: typeErrorMessage || DATE_TYPE_ERROR_INFO.message }));
|
19
|
+
}
|
20
|
+
if (Number.isNaN(Number(value))) {
|
21
|
+
return ctx.createError(Object.assign(Object.assign({}, INVALID_DATE_ERROR_INFO), { message: invalidDateErrorMessage || INVALID_DATE_ERROR_INFO.message }));
|
22
|
+
}
|
23
|
+
return compose(...rules)(value, ctx);
|
24
|
+
});
|
package/date/index.d.ts
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
export * from './date';
|
package/date/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
export * from './date';
|
@@ -0,0 +1,29 @@
|
|
1
|
+
import { Guard } from '../core';
|
2
|
+
/**
|
3
|
+
* @description Делает partial все object в схеме, независимо от уровня вложенности правил
|
4
|
+
* @param guard - любой guard
|
5
|
+
* @example
|
6
|
+
* ```ts
|
7
|
+
* const validate = deepPartial(
|
8
|
+
* object({
|
9
|
+
* name: string(),
|
10
|
+
* info: object({
|
11
|
+
* name: string(),
|
12
|
+
* info: object({ name: string() }),
|
13
|
+
* }),
|
14
|
+
* }),
|
15
|
+
* );
|
16
|
+
*
|
17
|
+
* // undefined
|
18
|
+
* const result = validate({ info: { info: {} } });
|
19
|
+
* ```
|
20
|
+
*/
|
21
|
+
export declare const deepPartial: <TValues>(guard: Guard<unknown, TValues, {}>) => (value: unknown, prevCtx?: Readonly<{
|
22
|
+
global: Readonly<{
|
23
|
+
values: TValues;
|
24
|
+
overrides: Readonly<{
|
25
|
+
objectIsPartial: boolean;
|
26
|
+
}>;
|
27
|
+
}>;
|
28
|
+
createError: ({ message, code }: import("../core").ErrorInfo) => import("../core").ValidationSimpleError<{}>;
|
29
|
+
}> | undefined) => import("../core").ValidationResult;
|
@@ -0,0 +1,21 @@
|
|
1
|
+
import { createRule } from '../core';
|
2
|
+
/**
|
3
|
+
* @description Делает partial все object в схеме, независимо от уровня вложенности правил
|
4
|
+
* @param guard - любой guard
|
5
|
+
* @example
|
6
|
+
* ```ts
|
7
|
+
* const validate = deepPartial(
|
8
|
+
* object({
|
9
|
+
* name: string(),
|
10
|
+
* info: object({
|
11
|
+
* name: string(),
|
12
|
+
* info: object({ name: string() }),
|
13
|
+
* }),
|
14
|
+
* }),
|
15
|
+
* );
|
16
|
+
*
|
17
|
+
* // undefined
|
18
|
+
* const result = validate({ info: { info: {} } });
|
19
|
+
* ```
|
20
|
+
*/
|
21
|
+
export const deepPartial = (guard) => createRule((value, prevCtx) => guard(value, Object.assign(Object.assign({}, prevCtx), { global: Object.assign(Object.assign({}, prevCtx.global), { overrides: Object.assign(Object.assign({}, prevCtx.global.overrides), { objectIsPartial: true }) }) })));
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './deepPartial';
|
@@ -0,0 +1 @@
|
|
1
|
+
export * from './deepPartial';
|
@@ -0,0 +1,11 @@
|
|
1
|
+
import { createErrorCode } from '../core';
|
2
|
+
export const EMAIL_REGEXP = /^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,}$/;
|
3
|
+
export const EMAIL_MAX_LENGTH = 256;
|
4
|
+
export const INVALID_EMAIL_ERROR_INFO = {
|
5
|
+
code: createErrorCode('email-invalid'),
|
6
|
+
message: 'Некорректный E-mail',
|
7
|
+
};
|
8
|
+
export const LENGTH_EMAIL_ERROR_INFO = {
|
9
|
+
code: createErrorCode('email-length'),
|
10
|
+
message: 'E-mail слишком длинный',
|
11
|
+
};
|
package/email/email.d.ts
ADDED
@@ -0,0 +1,28 @@
|
|
1
|
+
type EmailParams = {
|
2
|
+
/**
|
3
|
+
* @description Замена стандартного сообщения ошибки.
|
4
|
+
*/
|
5
|
+
message?: string;
|
6
|
+
/**
|
7
|
+
* @description Замена стандартного сообщения ошибки при превышении допустимого количества символов.
|
8
|
+
*/
|
9
|
+
invalidLengthMessage?: string;
|
10
|
+
};
|
11
|
+
/**
|
12
|
+
* @description Проверяет валидность email. Не работает с русскими доменами
|
13
|
+
* @example
|
14
|
+
* ```ts
|
15
|
+
* const validate = string(email());
|
16
|
+
* validate('example@mail.ru');
|
17
|
+
* ```
|
18
|
+
*/
|
19
|
+
export declare const email: <TValues>(params?: EmailParams) => (value: string, prevCtx?: Readonly<{
|
20
|
+
global: Readonly<{
|
21
|
+
values: TValues;
|
22
|
+
overrides: Readonly<{
|
23
|
+
objectIsPartial: boolean;
|
24
|
+
}>;
|
25
|
+
}>;
|
26
|
+
createError: ({ message, code }: import("../core").ErrorInfo) => import("../core").ValidationSimpleError<{}>;
|
27
|
+
}> | undefined) => import("../core").ValidationResult;
|
28
|
+
export {};
|
package/email/email.js
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
import { createRule } from '../core';
|
2
|
+
import { EMAIL_MAX_LENGTH, EMAIL_REGEXP, INVALID_EMAIL_ERROR_INFO, LENGTH_EMAIL_ERROR_INFO, } from './constants';
|
3
|
+
/**
|
4
|
+
* @description Проверяет валидность email. Не работает с русскими доменами
|
5
|
+
* @example
|
6
|
+
* ```ts
|
7
|
+
* const validate = string(email());
|
8
|
+
* validate('example@mail.ru');
|
9
|
+
* ```
|
10
|
+
*/
|
11
|
+
export const email = (params) => createRule((value, ctx) => {
|
12
|
+
if (!EMAIL_REGEXP.test(value)) {
|
13
|
+
return ctx.createError(Object.assign(Object.assign({}, INVALID_EMAIL_ERROR_INFO), { message: (params === null || params === void 0 ? void 0 : params.message) || INVALID_EMAIL_ERROR_INFO.message }));
|
14
|
+
}
|
15
|
+
if (value.length > EMAIL_MAX_LENGTH) {
|
16
|
+
return ctx.createError(Object.assign(Object.assign({}, LENGTH_EMAIL_ERROR_INFO), { message: (params === null || params === void 0 ? void 0 : params.invalidLengthMessage) || LENGTH_EMAIL_ERROR_INFO.message }));
|
17
|
+
}
|
18
|
+
return undefined;
|
19
|
+
});
|
package/email/index.d.ts
ADDED
package/email/index.js
ADDED
package/index.d.ts
CHANGED
@@ -1,20 +1,24 @@
|
|
1
|
-
export
|
2
|
-
export
|
3
|
-
export
|
4
|
-
export
|
5
|
-
export
|
6
|
-
export
|
7
|
-
export
|
8
|
-
export
|
9
|
-
export
|
10
|
-
export
|
11
|
-
export
|
12
|
-
export
|
13
|
-
export
|
14
|
-
export
|
15
|
-
export
|
16
|
-
export
|
17
|
-
export
|
18
|
-
export
|
19
|
-
export
|
20
|
-
export
|
1
|
+
export { object, OBJECT_TYPE_ERROR_INFO, type Schema, type SchemaValue, } from './object';
|
2
|
+
export { optional } from './optional';
|
3
|
+
export { string, STRING_TYPE_ERROR_INFO } from './string';
|
4
|
+
export { number, NAN_NUMBER_ERROR_INFO, NUMBER_TYPE_ERROR_INFO, INFINITY_NUMBER_ERROR_INFO, } from './number';
|
5
|
+
export { boolean, BOOLEAN_TYPE_ERROR_INFO } from './boolean';
|
6
|
+
export { array, ARRAY_TYPE_ERROR_INFO } from './array';
|
7
|
+
export { arrayItem } from './arrayItem';
|
8
|
+
export { deepPartial } from './deepPartial';
|
9
|
+
export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
|
10
|
+
export { or } from './or';
|
11
|
+
export { pattern, PATTERN_ERROR_CODE } from './pattern';
|
12
|
+
export { onlyNumber, ONLY_NUMBER_ERROR_CODE } from './onlyNumber';
|
13
|
+
export { toPlainError } from './toPlainError';
|
14
|
+
export { email, LENGTH_EMAIL_ERROR_INFO, INVALID_EMAIL_ERROR_INFO, } from './email';
|
15
|
+
export { mobilePhone, MOBILE_PHONE_ERROR_INFO } from './mobilePhone';
|
16
|
+
export { innUL, INN_UL_ERROR_INFO } from './innUL';
|
17
|
+
export { innIP, INN_IP_ERROR_INFO } from './innIP';
|
18
|
+
export { kpp, INVALID_KPP_ERROR_INFO } from './kpp';
|
19
|
+
export { snils, SNILS_ERROR_INFO } from './snils';
|
20
|
+
export { createRule, REQUIRED_ERROR_INFO, type ValidationRule } from './core';
|
21
|
+
export { ogrnUL, OGRN_UL_ERROR_INFO } from './ogrnUL';
|
22
|
+
export { ogrnIP, OGRN_IP_ERROR_INFO } from './ogrnIP';
|
23
|
+
export { any } from './any';
|
24
|
+
export { when } from './when';
|
package/index.js
CHANGED
@@ -1,20 +1,24 @@
|
|
1
|
-
export
|
2
|
-
export
|
3
|
-
export
|
4
|
-
export
|
5
|
-
export
|
6
|
-
export
|
7
|
-
export
|
8
|
-
export
|
9
|
-
export
|
10
|
-
export
|
11
|
-
export
|
12
|
-
export
|
13
|
-
export
|
14
|
-
export
|
15
|
-
export
|
16
|
-
export
|
17
|
-
export
|
18
|
-
export
|
19
|
-
export
|
20
|
-
export
|
1
|
+
export { object, OBJECT_TYPE_ERROR_INFO, } from './object';
|
2
|
+
export { optional } from './optional';
|
3
|
+
export { string, STRING_TYPE_ERROR_INFO } from './string';
|
4
|
+
export { number, NAN_NUMBER_ERROR_INFO, NUMBER_TYPE_ERROR_INFO, INFINITY_NUMBER_ERROR_INFO, } from './number';
|
5
|
+
export { boolean, BOOLEAN_TYPE_ERROR_INFO } from './boolean';
|
6
|
+
export { array, ARRAY_TYPE_ERROR_INFO } from './array';
|
7
|
+
export { arrayItem } from './arrayItem';
|
8
|
+
export { deepPartial } from './deepPartial';
|
9
|
+
export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
|
10
|
+
export { or } from './or';
|
11
|
+
export { pattern, PATTERN_ERROR_CODE } from './pattern';
|
12
|
+
export { onlyNumber, ONLY_NUMBER_ERROR_CODE } from './onlyNumber';
|
13
|
+
export { toPlainError } from './toPlainError';
|
14
|
+
export { email, LENGTH_EMAIL_ERROR_INFO, INVALID_EMAIL_ERROR_INFO, } from './email';
|
15
|
+
export { mobilePhone, MOBILE_PHONE_ERROR_INFO } from './mobilePhone';
|
16
|
+
export { innUL, INN_UL_ERROR_INFO } from './innUL';
|
17
|
+
export { innIP, INN_IP_ERROR_INFO } from './innIP';
|
18
|
+
export { kpp, INVALID_KPP_ERROR_INFO } from './kpp';
|
19
|
+
export { snils, SNILS_ERROR_INFO } from './snils';
|
20
|
+
export { createRule, REQUIRED_ERROR_INFO } from './core';
|
21
|
+
export { ogrnUL, OGRN_UL_ERROR_INFO } from './ogrnUL';
|
22
|
+
export { ogrnIP, OGRN_IP_ERROR_INFO } from './ogrnIP';
|
23
|
+
export { any } from './any';
|
24
|
+
export { when } from './when';
|