@astral/validations 4.10.0 → 4.11.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
@@ -26,6 +26,7 @@
26
26
  - [max](#max-string)
27
27
  - [email](#email)
28
28
  - [guid](#guid)
29
+ - [length](#length)
29
30
  - [pattern](#pattern)
30
31
  - [onlyNumber](#onlyNumber)
31
32
  - [containsNumbers](#containsNumbers)
@@ -412,6 +413,25 @@ validate('x56a4180-h5aa-42ec-a945-5fd21dec0538');
412
413
 
413
414
  ---
414
415
 
416
+ ### length
417
+
418
+ Проверяет значение на соответствие длине.
419
+
420
+ ```ts
421
+ import { string, length } from '@astral/validations';
422
+
423
+ const validate = string(length(5));
424
+
425
+ // undefined
426
+ validate('aaaaa');
427
+
428
+
429
+ // { message: 'Кол-во символов должно быть: 5' }
430
+ validate('abc');
431
+ ```
432
+
433
+ ---
434
+
415
435
  ### pattern
416
436
 
417
437
  Проверяет строку на соответствие регулярному выражению.
package/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export { boolean, BOOLEAN_TYPE_ERROR_INFO } from './boolean';
7
7
  export { array, ARRAY_TYPE_ERROR_INFO } from './array';
8
8
  export { arrayItem } from './arrayItem';
9
9
  export { deepPartial } from './deepPartial';
10
+ export { partial } from './partial';
10
11
  export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
11
12
  export { max, STRING_MAX_ERROR_CODE, ARRAY_MAX_ERROR_CODE, DATE_MAX_ERROR_CODE, NUMBER_MAX_ERROR_CODE, } from './max';
12
13
  export { integer, INTEGER_ERROR_INFO } from './integer';
@@ -20,6 +21,7 @@ export { containsDifferentCases, CONTAINS_DIFFERENT_CASES_ERROR_CODE, } from './
20
21
  export { toPlainError } from './toPlainError';
21
22
  export { email, LENGTH_EMAIL_ERROR_INFO, INVALID_EMAIL_ERROR_INFO, } from './email';
22
23
  export { guid, INVALID_GUID_ERROR_INFO } from './guid';
24
+ export { length, STRING_LENGTH_ERROR_CODE } from './length';
23
25
  export { mobilePhone, MOBILE_PHONE_ERROR_INFO } from './mobilePhone';
24
26
  export { innUL, INN_UL_ERROR_INFO } from './innUL';
25
27
  export { innIP, INN_IP_ERROR_INFO } from './innIP';
package/index.js CHANGED
@@ -7,6 +7,7 @@ export { boolean, BOOLEAN_TYPE_ERROR_INFO } from './boolean';
7
7
  export { array, ARRAY_TYPE_ERROR_INFO } from './array';
8
8
  export { arrayItem } from './arrayItem';
9
9
  export { deepPartial } from './deepPartial';
10
+ export { partial } from './partial';
10
11
  export { min, STRING_MIN_ERROR_CODE, ARRAY_MIN_ERROR_CODE, DATE_MIN_ERROR_CODE, NUMBER_MIN_ERROR_CODE, } from './min';
11
12
  export { max, STRING_MAX_ERROR_CODE, ARRAY_MAX_ERROR_CODE, DATE_MAX_ERROR_CODE, NUMBER_MAX_ERROR_CODE, } from './max';
12
13
  export { integer, INTEGER_ERROR_INFO } from './integer';
@@ -20,6 +21,7 @@ export { containsDifferentCases, CONTAINS_DIFFERENT_CASES_ERROR_CODE, } from './
20
21
  export { toPlainError } from './toPlainError';
21
22
  export { email, LENGTH_EMAIL_ERROR_INFO, INVALID_EMAIL_ERROR_INFO, } from './email';
22
23
  export { guid, INVALID_GUID_ERROR_INFO } from './guid';
24
+ export { length, STRING_LENGTH_ERROR_CODE } from './length';
23
25
  export { mobilePhone, MOBILE_PHONE_ERROR_INFO } from './mobilePhone';
24
26
  export { innUL, INN_UL_ERROR_INFO } from './innUL';
25
27
  export { innIP, INN_IP_ERROR_INFO } from './innIP';
@@ -0,0 +1,2 @@
1
+ import { ErrorCode } from '../core';
2
+ export declare const STRING_LENGTH_ERROR_CODE: ErrorCode;
@@ -0,0 +1,2 @@
1
+ import { createErrorCode } from '../core';
2
+ export const STRING_LENGTH_ERROR_CODE = createErrorCode('stringLength');
@@ -0,0 +1,2 @@
1
+ export * from './length';
2
+ export * from './constants';
@@ -0,0 +1,2 @@
1
+ export * from './length';
2
+ export * from './constants';
@@ -0,0 +1,22 @@
1
+ type LengthParams = {
2
+ /**
3
+ * @description Замена стандартного сообщения ошибки.
4
+ */
5
+ message?: string;
6
+ };
7
+ /**
8
+ * @description Проверяет значение на соответствие длине. Работает с: string
9
+ * @param len - целевой кол-во символов
10
+ * @example
11
+ * // Длина строки должна быть 5 символов
12
+ * const validate = string(length(5));
13
+ *
14
+ * // undefined
15
+ * validate('aaaaa')
16
+ *
17
+ * // error
18
+ * validate('va')
19
+ *
20
+ */
21
+ export declare const length: <TLastSchemaValues extends Record<string, unknown>>(len: number, params?: LengthParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
22
+ export {};
@@ -0,0 +1,26 @@
1
+ import { createRule } from '../core';
2
+ import { STRING_LENGTH_ERROR_CODE } from './constants';
3
+ /**
4
+ * @description Проверяет значение на соответствие длине. Работает с: string
5
+ * @param len - целевой кол-во символов
6
+ * @example
7
+ * // Длина строки должна быть 5 символов
8
+ * const validate = string(length(5));
9
+ *
10
+ * // undefined
11
+ * validate('aaaaa')
12
+ *
13
+ * // error
14
+ * validate('va')
15
+ *
16
+ */
17
+ export const length = (len, params) => createRule((value, ctx) => {
18
+ const currentLength = value.trim().length;
19
+ if (currentLength !== len) {
20
+ return ctx.createError({
21
+ code: STRING_LENGTH_ERROR_CODE,
22
+ message: (params === null || params === void 0 ? void 0 : params.message) || `Кол-во символов должно быть: ${len}`,
23
+ });
24
+ }
25
+ return undefined;
26
+ });
package/object/object.js CHANGED
@@ -37,8 +37,7 @@ export const object = (schema) => createGuard((value, ctx, { typeErrorMessage, i
37
37
  const schemaEntries = Object.entries(schema);
38
38
  const isOptional = context.global.overrides.objectIsPartial || isPartial;
39
39
  return schemaEntries.reduce((errorMap, [key, rule]) => {
40
- const isGuard = 'define' in rule;
41
- const callRule = isGuard && isOptional ? optional(rule) : rule;
40
+ const callRule = isOptional ? optional(rule) : rule;
42
41
  errorMap[key] = callRecursiveRule(callRule, value[key], context);
43
42
  return errorMap;
44
43
  }, {});
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import isPlainObject from 'is-plain-obj';
11
11
  import { callAsyncRule as callAsyncRecursiveRule, createContext, createErrorMap, createGuard, } from '../../core';
12
- import { optional } from '../../optional';
12
+ import { optionalAsync } from '../../optional';
13
13
  import { isEmptyErrors } from '../isEmptyErrors';
14
14
  import { OBJECT_TYPE_ERROR_INFO } from '../constants';
15
15
  // TODO: необходимо реализовать переиспользование логики между object и objectAsync
@@ -55,8 +55,7 @@ export const objectAsync = (schema) => createGuard((value, ctx, { typeErrorMessa
55
55
  const schemaEntries = Object.entries(schema);
56
56
  const isOptional = context.global.overrides.objectIsPartial || isPartial;
57
57
  const results = yield Promise.all(schemaEntries.map(([key, rule]) => {
58
- const isGuard = 'define' in rule;
59
- const callRule = isGuard && isOptional ? optional(rule) : rule;
58
+ const callRule = isOptional ? optionalAsync(rule) : rule;
60
59
  return callAsyncRecursiveRule(callRule, value[key], context);
61
60
  }));
62
61
  return results.reduce((errorMap, validationResult, index) => {
@@ -1,6 +1,6 @@
1
- import { AsyncIndependentValidationRule, AsyncValidationRule } from '../../core';
1
+ import { AsyncIndependentValidationRule, AsyncValidationRule, ValidationRule } from '../../core';
2
2
  /**
3
3
  * @description Выключает проверку на required в guard. Предназначен для асинхронных правил.
4
4
  * @example object({ name: optionalAsync(stringAsync(min(22))) })
5
5
  */
6
- export declare const optionalAsync: <TLastSchemaValues extends Record<string, unknown>>(rule: AsyncValidationRule<unknown, TLastSchemaValues>) => AsyncIndependentValidationRule<unknown, TLastSchemaValues>;
6
+ export declare const optionalAsync: <TLastSchemaValues extends Record<string, unknown>>(rule: AsyncValidationRule<unknown, TLastSchemaValues> | ValidationRule<unknown, TLastSchemaValues>) => AsyncIndependentValidationRule<unknown, TLastSchemaValues>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astral/validations",
3
- "version": "4.10.0",
3
+ "version": "4.11.0",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {