@astral/validations 4.13.3 → 4.14.1

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/README.md CHANGED
@@ -71,6 +71,7 @@
71
71
  - [Common](#common)
72
72
  - [optional](#optional)
73
73
  - [when. Условная валидация](#when-условная-валидация)
74
+ - [enabled. Условная валидация](#enabled-условная-валидация)
74
75
  - [transform](#transform)
75
76
  - [or](#or)
76
77
  - [Async](#async)
@@ -1607,6 +1608,57 @@ toPrettyError(
1607
1608
  validate({ name: 'Vasya' })
1608
1609
  );
1609
1610
 
1611
+ // undefined
1612
+ validate({ name: 'Kolya' });
1613
+ ```
1614
+ ---
1615
+
1616
+ ## enabled. Условная валидация
1617
+
1618
+ Позволяет определять условные валидации без выбора альтернативной схемы. Является упрощением when с otherwise = any().
1619
+
1620
+ ```ts
1621
+ type Values = { name: string; isAgree: boolean };
1622
+
1623
+ const validate = object<Values>({
1624
+ name: enabled({
1625
+ is: (_, ctx) => Boolean(ctx.values?.isAgree),
1626
+ then: string(),
1627
+ }),
1628
+ isAgree: optional(boolean()),
1629
+ });
1630
+
1631
+ // undefined
1632
+ validate({ isAgree: false, name: '' });
1633
+
1634
+ // { name: 'Обязательно' }
1635
+ toPrettyError(
1636
+ validate({ isAgree: true, name: '' })
1637
+ );
1638
+ ```
1639
+
1640
+ Enabled для ветки объекта:
1641
+ ```ts
1642
+ type ValuesInfo = { surname: string };
1643
+
1644
+ type Values = {
1645
+ name: string;
1646
+ info?: ValuesInfo;
1647
+ };
1648
+
1649
+ const validate = object<Values>({
1650
+ name: string(),
1651
+ info: enabled({
1652
+ is: (_, ctx) => ctx.values?.name === 'Vasya',
1653
+ then: object<ValuesInfo>({ surname: string() }),
1654
+ }),
1655
+ });
1656
+
1657
+ // { info: 'Обязательно' }
1658
+ toPrettyError(
1659
+ validate({ name: 'Vasya' })
1660
+ );
1661
+
1610
1662
  // undefined
1611
1663
  validate({ name: 'Kolya' });
1612
1664
  ```
package/array/array.d.ts CHANGED
@@ -12,4 +12,4 @@ import { type ValidationRule } from '../core';
12
12
  * validateArray(value);
13
13
  * ```
14
14
  */
15
- export declare const array: <TItem extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(...rules: ValidationRule<TItem[], TLastSchemaValues>[]) => import("../core").Guard<TLastSchemaValues, {}>;
15
+ export declare const array: <TItem extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(...rules: ValidationRule<Array<TItem>, TLastSchemaValues>[]) => import("../core").Guard<TLastSchemaValues, {}>;
@@ -3,4 +3,4 @@ import { type IndependentValidationRule, type ValidationRule } from '../rule';
3
3
  * @description Объединяет переданные правила в цепочку правил, останавливает выполнение цепочки, если появилась ошибка. Выполняет правила слева направо
4
4
  * @example compose(min(), max());
5
5
  */
6
- export declare const compose: <ValidationType, TLastSchemaValues extends Record<string, unknown>>(...rules: (IndependentValidationRule<ValidationType, TLastSchemaValues> | ValidationRule<ValidationType, TLastSchemaValues>)[]) => IndependentValidationRule<ValidationType, Record<string, unknown>>;
6
+ export declare const compose: <ValidationType, TLastSchemaValues extends Record<string, unknown>>(...rules: Array<IndependentValidationRule<ValidationType, TLastSchemaValues> | ValidationRule<ValidationType, TLastSchemaValues>>) => IndependentValidationRule<ValidationType, Record<string, unknown>>;
@@ -3,4 +3,4 @@ import { type AsyncIndependentValidationRule, type AsyncValidationRule, type Ind
3
3
  * Объединяет переданные асинхронные правила в цепочку правил, останавливает выполнение цепочки, если появилась ошибка. Выполняет правила слева направо
4
4
  * @example composeAsync(stringAsync(), max());
5
5
  */
6
- export declare const composeAsync: <ValidationType, TLastSchemaValues extends Record<string, unknown>>(...rules: (IndependentValidationRule<ValidationType, TLastSchemaValues> | AsyncIndependentValidationRule<ValidationType, TLastSchemaValues> | ValidationRule<ValidationType, TLastSchemaValues> | AsyncValidationRule<ValidationType, TLastSchemaValues>)[]) => AsyncIndependentValidationRule<ValidationType, Record<string, unknown>>;
6
+ export declare const composeAsync: <ValidationType, TLastSchemaValues extends Record<string, unknown>>(...rules: Array<IndependentValidationRule<ValidationType, TLastSchemaValues> | AsyncIndependentValidationRule<ValidationType, TLastSchemaValues> | ValidationRule<ValidationType, TLastSchemaValues> | AsyncValidationRule<ValidationType, TLastSchemaValues>>) => AsyncIndependentValidationRule<ValidationType, Record<string, unknown>>;
@@ -30,5 +30,5 @@ type RuleExecutor<ValidationType extends ValidationTypes, TLastSchemaValues exte
30
30
  * }, params);
31
31
  * ```
32
32
  */
33
- export declare const createRule: <ValidationType extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(executor: RuleExecutor<ValidationType, TLastSchemaValues>, commonParams?: CommonRuleParams<ValidationType> | undefined) => (value: ValidationType, prevCtx?: ValidationContext<TLastSchemaValues> | undefined) => ValidationResult;
33
+ export declare const createRule: <ValidationType extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(executor: RuleExecutor<ValidationType, TLastSchemaValues>, commonParams?: CommonRuleParams<ValidationType>) => (value: Parameters<IndependentValidationRule<ValidationType, TLastSchemaValues>>[0], prevCtx?: Parameters<IndependentValidationRule<ValidationType, TLastSchemaValues>>[1]) => ReturnType<IndependentValidationRule<ValidationType, TLastSchemaValues>>;
34
34
  export {};
@@ -7,5 +7,5 @@ export declare const required: ({ message, }?: {
7
7
  * @description Кастомное сообщение ошибки
8
8
  * @default Обязательно
9
9
  */
10
- message?: string | undefined;
10
+ message?: string;
11
11
  }) => (value: unknown, prevCtx?: import("../..").ValidationContext<{}> | undefined) => import("../..").ValidationResult;
@@ -18,4 +18,4 @@ import { type Guard } from '../core';
18
18
  * const result = validate({ info: { info: {} } });
19
19
  * ```
20
20
  */
21
- export declare const deepPartial: <TLastSchemaValues extends Record<string, unknown>>(guard: Guard<TLastSchemaValues, {}>) => (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
21
+ export declare const deepPartial: <TLastSchemaValues extends Record<string, unknown>>(guard: Guard<TLastSchemaValues>) => (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
@@ -0,0 +1,34 @@
1
+ import { type ValidationContext, type ValidationRule } from '../core';
2
+ type Params<TLastSchemaValues extends Record<string, unknown>> = {
3
+ /**
4
+ * @description Условие для включения схемы
5
+ */
6
+ is: (value: unknown, ctx: ValidationContext<TLastSchemaValues>) => boolean;
7
+ /**
8
+ * Правило валидации, применяемая если is === true
9
+ */
10
+ then: ValidationRule<unknown, TLastSchemaValues>;
11
+ };
12
+ /**
13
+ * @description Позволяет указывать условные валидации
14
+ * @example
15
+ * ```ts
16
+ * type Values = { name: string; isAgree: boolean };
17
+ *
18
+ * const validate = object<Values>({
19
+ * name: enabled({
20
+ * is: (_, ctx) => ctx.global.values.isAgree,
21
+ * then: string(),
22
+ * }),
23
+ * isAgree: optional(boolean()),
24
+ * });
25
+ *
26
+ * // undefined
27
+ * const result1 = validate({ isAgree: false, name: '' });
28
+ *
29
+ * // Required error для name
30
+ * const result2 = validate({ isAgree: true, name: '' });
31
+ * ```
32
+ */
33
+ export declare const enabled: <TLastSchemaValues extends Record<string, unknown>>({ is, then, }: Params<TLastSchemaValues>) => (value: unknown, prevCtx?: ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
34
+ export {};
@@ -0,0 +1,31 @@
1
+ import { any } from '../any';
2
+ import { callRule, createRule, } from '../core';
3
+ /**
4
+ * @description Позволяет указывать условные валидации
5
+ * @example
6
+ * ```ts
7
+ * type Values = { name: string; isAgree: boolean };
8
+ *
9
+ * const validate = object<Values>({
10
+ * name: enabled({
11
+ * is: (_, ctx) => ctx.global.values.isAgree,
12
+ * then: string(),
13
+ * }),
14
+ * isAgree: optional(boolean()),
15
+ * });
16
+ *
17
+ * // undefined
18
+ * const result1 = validate({ isAgree: false, name: '' });
19
+ *
20
+ * // Required error для name
21
+ * const result2 = validate({ isAgree: true, name: '' });
22
+ * ```
23
+ */
24
+ export const enabled = ({ is, then, }) => {
25
+ return createRule((value, ctx) => {
26
+ if (is(value, ctx)) {
27
+ return callRule(then, value, ctx);
28
+ }
29
+ return callRule(any(), value, ctx);
30
+ });
31
+ };
@@ -0,0 +1 @@
1
+ export * from './enabled';
@@ -0,0 +1 @@
1
+ export * from './enabled';
package/index.d.ts CHANGED
@@ -44,3 +44,4 @@ export { any } from './any';
44
44
  export { when } from './when';
45
45
  export { toPrettyError } from './toPrettyError';
46
46
  export { transform } from './transform';
47
+ export { enabled } from './enabled';
package/index.js CHANGED
@@ -44,3 +44,4 @@ export { any } from './any';
44
44
  export { when } from './when';
45
45
  export { toPrettyError } from './toPrettyError';
46
46
  export { transform } from './transform';
47
+ export { enabled } from './enabled';
@@ -44,7 +44,7 @@ import { OBJECT_TYPE_ERROR_INFO } from '../constants';
44
44
  * });
45
45
  * ```
46
46
  */
47
- export const objectAsync = (schema) => createGuard((value, ctx, { typeErrorMessage, isPartial }) => __awaiter(void 0, void 0, void 0, function* () {
47
+ export const objectAsync = (schema) => createGuard((value_1, ctx_1, _a) => __awaiter(void 0, [value_1, ctx_1, _a], void 0, function* (value, ctx, { typeErrorMessage, isPartial }) {
48
48
  const context = createContext(ctx, value, {
49
49
  lastSchemaValue: value,
50
50
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astral/validations",
3
- "version": "4.13.3",
3
+ "version": "4.14.1",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {
@@ -3,4 +3,4 @@ import { type AsyncValidationRule, type ValidationRule } from '../../core';
3
3
  * Позволяет использовать для валидации асинхронные правила
4
4
  * @example stringAsync(async () => undefined)
5
5
  */
6
- export declare const stringAsync: <TLastSchemaValues extends Record<string, unknown>>(...rules: (ValidationRule<string, TLastSchemaValues> | AsyncValidationRule<string, TLastSchemaValues>)[]) => import("../../core").AsyncGuard<TLastSchemaValues, {}>;
6
+ export declare const stringAsync: <TLastSchemaValues extends Record<string, unknown>>(...rules: Array<ValidationRule<string, TLastSchemaValues> | AsyncValidationRule<string, TLastSchemaValues>>) => import("../../core").AsyncGuard<TLastSchemaValues, {}>;
@@ -15,7 +15,7 @@ import { STRING_TYPE_ERROR_INFO } from '../constants';
15
15
  * Позволяет использовать для валидации асинхронные правила
16
16
  * @example stringAsync(async () => undefined)
17
17
  */
18
- export const stringAsync = (...rules) => createGuard((value, ctx, { typeErrorMessage }) => __awaiter(void 0, void 0, void 0, function* () {
18
+ export const stringAsync = (...rules) => createGuard((value_1, ctx_1, _a) => __awaiter(void 0, [value_1, ctx_1, _a], void 0, function* (value, ctx, { typeErrorMessage }) {
19
19
  if (!isString(value)) {
20
20
  return ctx.createError(Object.assign(Object.assign({}, STRING_TYPE_ERROR_INFO), { message: typeErrorMessage || STRING_TYPE_ERROR_INFO.message }));
21
21
  }