@astral/validations 4.9.2 → 4.10.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
@@ -47,6 +47,7 @@
47
47
  - [date](#date)
48
48
  - [min](#min-date)
49
49
  - [max](#max-date)
50
+ - [minYearsOld](#min-years-old-date)
50
51
  - [boolean](#boolean)
51
52
  - [object](#object)
52
53
  - [partial](#partial)
@@ -874,6 +875,30 @@ validate(new Date('02-01-2021'));
874
875
 
875
876
  ---
876
877
 
878
+ ### #min years old date
879
+
880
+ Принимает возраст и вычитает переданное количество лет из текущей даты. Позволяет кастомизировать текст ошибки.
881
+
882
+ ```ts
883
+ import { date, minYearsOld } from '@astral/validations';
884
+
885
+ const validate = date(
886
+ minYearsOld(18, {
887
+ customErrorMessage:
888
+ 'Только совершеннолетние могут воспользоваться данной услугой',
889
+ }),
890
+ );
891
+
892
+ // { message: 'Только совершеннолетние могут воспользоваться данной услугой' }
893
+ validate(new Date('15.11.2022'));
894
+
895
+ // undefined
896
+ validate(new Date('10.10.2005'));
897
+
898
+ ```
899
+
900
+ ---
901
+
877
902
  ## boolean
878
903
 
879
904
  - Возвращает ошибку если:
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';
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';
@@ -0,0 +1,4 @@
1
+ import { ErrorCode } from '../core';
2
+ export declare const BIRTH_DATE_MAX_ERROR_CODE: ErrorCode;
3
+ export declare const BIRTH_DATE_MIN_ERROR_CODE: ErrorCode;
4
+ export declare const BIRTH_DATE_MIN: Date;
@@ -0,0 +1,4 @@
1
+ import { createErrorCode } from '../core';
2
+ export const BIRTH_DATE_MAX_ERROR_CODE = createErrorCode('birth-date-max');
3
+ export const BIRTH_DATE_MIN_ERROR_CODE = createErrorCode('birth-date-min');
4
+ export const BIRTH_DATE_MIN = new Date('01.01.1900');
@@ -0,0 +1,2 @@
1
+ export * from './minYearsOld';
2
+ export * from './constants';
@@ -0,0 +1,2 @@
1
+ export * from './minYearsOld';
2
+ export * from './constants';
@@ -0,0 +1,24 @@
1
+ type MinYearsOldParams = {
2
+ /**
3
+ * @description Кастомное сообщение ошибки
4
+ */
5
+ customErrorMessage: string;
6
+ };
7
+ /**
8
+ * @description Проверяет дату рождения на соответствие условию. Работает с date.
9
+ * @param age - ограничение по возрасту (коло-во лет, вычитаемое из текущей даты для валидации)
10
+ * @param params - объект параметров
11
+ * @example
12
+ * ```ts
13
+
14
+ *
15
+ * const validate = date(
16
+ * minYearsOld(18, {
17
+ * customMessage:
18
+ * 'Только совершеннолетние могут воспользоваться данной услугой',
19
+ * }),
20
+ * );
21
+ * ```
22
+ */
23
+ export declare function minYearsOld<ValidationType, TLastSchemaValues extends Record<string, unknown> = {}>(age: number, params?: MinYearsOldParams): (value: ValidationType, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
24
+ export {};
@@ -0,0 +1,44 @@
1
+ import { createRule } from '../core';
2
+ import { BIRTH_DATE_MAX_ERROR_CODE, BIRTH_DATE_MIN, BIRTH_DATE_MIN_ERROR_CODE, } from './constants';
3
+ /**
4
+ * @description Проверяет дату рождения на соответствие условию. Работает с date.
5
+ * @param age - ограничение по возрасту (коло-во лет, вычитаемое из текущей даты для валидации)
6
+ * @param params - объект параметров
7
+ * @example
8
+ * ```ts
9
+
10
+ *
11
+ * const validate = date(
12
+ * minYearsOld(18, {
13
+ * customMessage:
14
+ * 'Только совершеннолетние могут воспользоваться данной услугой',
15
+ * }),
16
+ * );
17
+ * ```
18
+ */
19
+ export function minYearsOld(age, params) {
20
+ return createRule((value, ctx) => {
21
+ const getMessage = (typeMessage) => {
22
+ const message = params === null || params === void 0 ? void 0 : params.customErrorMessage;
23
+ return message ? message : typeMessage;
24
+ };
25
+ const threshold = new Date();
26
+ threshold.setFullYear(threshold.getFullYear() - age);
27
+ if (value instanceof Date && value > BIRTH_DATE_MIN) {
28
+ if (value > threshold) {
29
+ return ctx.createError({
30
+ code: BIRTH_DATE_MAX_ERROR_CODE,
31
+ message: getMessage(`Вам должно быть больше ${age} лет`),
32
+ });
33
+ }
34
+ return undefined;
35
+ }
36
+ if (value < BIRTH_DATE_MIN) {
37
+ return ctx.createError({
38
+ code: BIRTH_DATE_MIN_ERROR_CODE,
39
+ message: getMessage(`Не ранее ${BIRTH_DATE_MIN}`),
40
+ });
41
+ }
42
+ return undefined;
43
+ });
44
+ }
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.9.2",
3
+ "version": "4.10.1",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {