@astral/validations 3.0.0-beta.4 → 3.1.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/README.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - [min](#min-number)
21
21
  - [max](#max-number)
22
22
  - [integer](#integer)
23
+ - [positiveNumber](#positivenumber)
23
24
  - [string](#string)
24
25
  - [min](#min-string)
25
26
  - [max](#max-string)
@@ -57,8 +58,11 @@
57
58
  - [or](#or)
58
59
  - [Integrations](#integrations)
59
60
  - [react-hook-form](#react-hook-form)
60
- - [Error message customization](#error-message-customization)
61
- - [Exclusion managing](#exclusion-managing)
61
+ - [Guides](#guides)
62
+ - [Переиспользование объектов схемы](#переиспользование-объектов-схемы)
63
+ - [Переиспользование объектов схемы, с условной валидацией и зависимыми полями](#переиспользование-объектов-схемы-с-условной-валидацией-и-зависимыми-полями)
64
+ - [Error message customization](#error-message-customization)
65
+ - [Exclusion managing](#exclusion-managing)
62
66
 
63
67
  ---
64
68
 
@@ -76,7 +80,9 @@ yarn add @astral/validations
76
80
 
77
81
  # Basic usage
78
82
 
79
- Валидация объекта с вложенным массивом
83
+ Валидация объекта с вложенным массивом.
84
+
85
+ ### [Codesandbox](https://codesandbox.io/s/astral-validations-basic-usage-jkpjr5?file=/main.ts)
80
86
 
81
87
  ```ts
82
88
  import {
@@ -258,6 +264,27 @@ validate(3.14)
258
264
 
259
265
  ---
260
266
 
267
+ ### positiveNumber
268
+
269
+ Проверяет является ли значение положительным числом.
270
+
271
+ ```ts
272
+ import { number, positiveNumber } from '@astral/validations';
273
+
274
+ const validate = number(positiveNumber(3));
275
+
276
+ // undefined
277
+ validate(3)
278
+
279
+ // { message: 'Только положительное числа' }
280
+ validate(0)
281
+
282
+ // { message: 'Только положительное числа' }
283
+ validate(-1)
284
+ ```
285
+
286
+ ---
287
+
261
288
  ## string
262
289
 
263
290
  - Возвращает ошибку если:
@@ -1208,6 +1235,8 @@ validate(new Date())
1208
1235
 
1209
1236
  Для интеграции с react-hook-form необходимо использовать пакет ```@astral/validations-react-hook-form-resolver```.
1210
1237
 
1238
+ ### [Codesandbox](https://codesandbox.io/s/astral-validations-react-hook-form-tnq4of?file=/src/Form.tsx)
1239
+
1211
1240
  ```tsx
1212
1241
  import { object, string, optional } from '@astral/validations';
1213
1242
  import { resolver } from '@astral/validations-react-hook-form-resolver';
@@ -1246,7 +1275,85 @@ const Form = () => {
1246
1275
  };
1247
1276
  ```
1248
1277
 
1249
- # Error message customization
1278
+ # Guides
1279
+
1280
+
1281
+ ## Переиспользование объектов схемы
1282
+
1283
+ ```ts
1284
+ type Address = {
1285
+ street: string;
1286
+ };
1287
+
1288
+ const address = object<Address>({ street: string() });
1289
+
1290
+ type Organization = {
1291
+ address: Address;
1292
+ };
1293
+
1294
+ const organization = object<Organization>({ address });
1295
+
1296
+ type Values = {
1297
+ name: string;
1298
+ org: Organization;
1299
+ };
1300
+
1301
+ const validateValues = object<Values>({
1302
+ name: string(),
1303
+ org: organization,
1304
+ });
1305
+ ```
1306
+
1307
+ ---
1308
+
1309
+ ## Переиспользование объектов схемы, с условной валидацией и зависимыми полями
1310
+
1311
+ ```ts
1312
+ type RusOrganization = {
1313
+ inn: string;
1314
+ isIP: boolean;
1315
+ };
1316
+
1317
+ type EngOrganization = {
1318
+ name: string;
1319
+ };
1320
+
1321
+ type Values = {
1322
+ isRus: boolean;
1323
+ org: { data: RusOrganization | EngOrganization };
1324
+ };
1325
+
1326
+ // второй параметр generic - это глобально валидируемое значение. Для формы это весь values
1327
+ const rusOrganization = object<RusOrganization, Values>({
1328
+ inn: string(
1329
+ // автоматический вывод типа для ctx.global.values
1330
+ when({
1331
+ is: (_, ctx) => Boolean(ctx.global.values.isRus),
1332
+ then: rusOrganization,
1333
+ otherwise: engOrganization,
1334
+ }),
1335
+ ),
1336
+ isIP: optional(boolean()),
1337
+ });
1338
+
1339
+ const engOrganization = object<EngOrganization, Values>({ name: string() });
1340
+
1341
+ // необходимо явно указать Values для типизации ctx.global.values
1342
+ const organization = when<Values>({
1343
+ is: (_, ctx) => Boolean(ctx.global.values.isRus),
1344
+ then: rusOrganization,
1345
+ otherwise: engOrganization,
1346
+ });
1347
+
1348
+ const validate = object<Values, Values>({
1349
+ isRus: optional(boolean()),
1350
+ org: organization,
1351
+ });
1352
+ ```
1353
+
1354
+ ---
1355
+
1356
+ ## Error message customization
1250
1357
 
1251
1358
  Сообщения об ошибках по умолчанию могут быть заменены на пользовательские.
1252
1359
  Для этого необходимо использовать параметры `message` или `getMessage` у валидационных методов:
@@ -1269,7 +1376,7 @@ validateKPP('123123');
1269
1376
 
1270
1377
  ---
1271
1378
 
1272
- # Exclusion managing
1379
+ ## Exclusion managing
1273
1380
 
1274
1381
  Метод `exclude` предоставляет возможность обхода валидации для конкретного значения.
1275
1382
  Если функция вернет `true`,
package/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export { deepPartial } from './deepPartial';
10
10
  export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
11
11
  export { max, STRING_MAX_ERROR_CODE, ARRAY_MAX_ERROR_CODE, DATE_MAX_ERROR_CODE, NUMBER_MAX_ERROR_CODE, } from './max';
12
12
  export { integer, INTEGER_ERROR_INFO } from './integer';
13
+ export { positiveNumber, POSITIVE_NUMBER_ERROR_INFO } from './positiveNumber';
13
14
  export { or } from './or';
14
15
  export { pattern, PATTERN_ERROR_CODE } from './pattern';
15
16
  export { onlyNumber, ONLY_NUMBER_ERROR_CODE } from './onlyNumber';
package/index.js CHANGED
@@ -10,6 +10,7 @@ export { deepPartial } from './deepPartial';
10
10
  export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
11
11
  export { max, STRING_MAX_ERROR_CODE, ARRAY_MAX_ERROR_CODE, DATE_MAX_ERROR_CODE, NUMBER_MAX_ERROR_CODE, } from './max';
12
12
  export { integer, INTEGER_ERROR_INFO } from './integer';
13
+ export { positiveNumber, POSITIVE_NUMBER_ERROR_INFO } from './positiveNumber';
13
14
  export { or } from './or';
14
15
  export { pattern, PATTERN_ERROR_CODE } from './pattern';
15
16
  export { onlyNumber, ONLY_NUMBER_ERROR_CODE } from './onlyNumber';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astral/validations",
3
- "version": "3.0.0-beta.4",
3
+ "version": "3.1.0",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {
@@ -0,0 +1,2 @@
1
+ import { ErrorInfo } from '../core';
2
+ export declare const POSITIVE_NUMBER_ERROR_INFO: ErrorInfo;
@@ -0,0 +1,5 @@
1
+ import { createErrorCode } from '../core';
2
+ export const POSITIVE_NUMBER_ERROR_INFO = {
3
+ code: createErrorCode('positive-number'),
4
+ message: 'Только положительные числа',
5
+ };
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './positiveNumber';
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './positiveNumber';
@@ -0,0 +1,25 @@
1
+ type PositiveNumberParams = {
2
+ /**
3
+ * @description Замена стандартного сообщения ошибки.
4
+ */
5
+ message?: string;
6
+ };
7
+ /**
8
+ * @description
9
+ * Проверяет является ли значение положительным числом.
10
+ * @example
11
+ * ```ts
12
+ * const validate = number(positiveNumber(3));
13
+ *
14
+ * // undefined
15
+ * validate(3)
16
+ *
17
+ * // { message: 'Только положительное числа' }
18
+ * validate(0)
19
+ *
20
+ * // { message: 'Только положительное числа' }
21
+ * validate(-1)
22
+ * ```
23
+ */
24
+ export declare const positiveNumber: <TValues>(params?: PositiveNumberParams) => (value: number, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
25
+ export {};
@@ -0,0 +1,31 @@
1
+ import { createRule } from '../core';
2
+ import { POSITIVE_NUMBER_ERROR_INFO } from './constants';
3
+ const isPositiveNumber = (number) => {
4
+ return number > 0;
5
+ };
6
+ /**
7
+ * @description
8
+ * Проверяет является ли значение положительным числом.
9
+ * @example
10
+ * ```ts
11
+ * const validate = number(positiveNumber(3));
12
+ *
13
+ * // undefined
14
+ * validate(3)
15
+ *
16
+ * // { message: 'Только положительное числа' }
17
+ * validate(0)
18
+ *
19
+ * // { message: 'Только положительное числа' }
20
+ * validate(-1)
21
+ * ```
22
+ */
23
+ export const positiveNumber = (params) => createRule((value, ctx) => {
24
+ if (!isPositiveNumber(value)) {
25
+ return ctx.createError({
26
+ message: (params === null || params === void 0 ? void 0 : params.message) || POSITIVE_NUMBER_ERROR_INFO.message,
27
+ code: POSITIVE_NUMBER_ERROR_INFO.code,
28
+ });
29
+ }
30
+ return undefined;
31
+ });