@astral/validations 4.8.0 → 4.9.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
@@ -28,6 +28,9 @@
28
28
  - [guid](#guid)
29
29
  - [pattern](#pattern)
30
30
  - [onlyNumber](#onlyNumber)
31
+ - [containsNumbers](#containsNumbers)
32
+ - [containsDifferentCases](#containsDifferentCases)
33
+ - [containsPunctuationMarks](#containsPunctuationMarks)
31
34
  - [snils](#snils)
32
35
  - [mobilePhone](#mobilePhone)
33
36
  - [innUL](#innUL)
@@ -448,6 +451,62 @@ validate('-1.2345')
448
451
 
449
452
  ---
450
453
 
454
+ ### containsNumbers
455
+
456
+ Проверяет на наличие чисел в строке
457
+
458
+ ```ts
459
+ import { string, containsNumbers } from '@astral/validations';
460
+
461
+ const validate = string(containsNumbers());
462
+
463
+ // undefined
464
+ validate('test12345')
465
+
466
+ // { message: 'Строка должна содержать числа' }
467
+ validate('test')
468
+ ```
469
+
470
+ ---
471
+
472
+ ### containsDifferentCases
473
+
474
+ Проверяет на наличие в строке символов разных регистров
475
+
476
+ ```ts
477
+ import { string, containsDifferentCases } from '@astral/validations';
478
+
479
+ const validate = string(containsDifferentCases());
480
+
481
+ // undefined
482
+ validate('testTEST')
483
+ validate('тестТЕСТ')
484
+
485
+ // { message: 'Строка должна содержать символы разного регистра' }
486
+ validate('test')
487
+ validate('ТЕСТ')
488
+ ```
489
+
490
+ ---
491
+
492
+ ### containsPunctuationMarks
493
+
494
+ Проверяет на наличие в строке знаков пунктуации !$%&’()+,-./:;<=>?@[]^_{|}”
495
+
496
+ ```ts
497
+ import { string, containsPunctuationMarks } from '@astral/validations';
498
+
499
+ const validate = string(containsPunctuationMarks());
500
+
501
+ // undefined
502
+ validate('test?')
503
+
504
+ // { message: 'Строка должна содержать знаки пунктуации' }
505
+ validate('test')
506
+ ```
507
+
508
+ ---
509
+
451
510
  ### snils
452
511
 
453
512
  Проверяет валиден ли СНИЛС
@@ -1491,6 +1550,7 @@ validate(new Date())
1491
1550
  Guard, поддерживающие асинхронную валидацию имеют постфиксы ```async```:
1492
1551
  - ```objectAsync```
1493
1552
  - ```stringAsync```
1553
+ - ```optionalAsync```
1494
1554
 
1495
1555
  Пример:
1496
1556
 
@@ -1514,9 +1574,21 @@ const validate = objectAsync<Values>({
1514
1574
  message: 'Nickname занят',
1515
1575
  });
1516
1576
  }),
1577
+ fullName: optionalAsync(stringAsync(async (value, ctx) => {
1578
+ const nicknameIsAvailable = await checkNickname(value);
1579
+
1580
+ if (nicknameIsAvailable) {
1581
+ return undefined;
1582
+ }
1583
+
1584
+ return ctx.createError({
1585
+ code: 'nickname-available',
1586
+ message: 'Nickname занят',
1587
+ });
1588
+ })),
1517
1589
  });
1518
1590
 
1519
- const result = await validate({ phone: '79308999999', nickname: 'Vasya' });
1591
+ const result = await validate({ phone: '79308999999', nickname: 'Vasya', fullName: '' });
1520
1592
 
1521
1593
  // { nickname: 'Nickname занят' }
1522
1594
  toPrettyError(result);
@@ -0,0 +1,2 @@
1
+ import { ErrorCode } from '../core';
2
+ export declare const CONTAINS_DIFFERENT_CASES_ERROR_CODE: ErrorCode;
@@ -0,0 +1,2 @@
1
+ import { createErrorCode } from '../core';
2
+ export const CONTAINS_DIFFERENT_CASES_ERROR_CODE = createErrorCode('containsDifferentCases');
@@ -0,0 +1,16 @@
1
+ type ContainsDifferentCasesParams = {
2
+ /**
3
+ * @description Замена стандартного сообщения ошибки.
4
+ */
5
+ message?: string;
6
+ };
7
+ /**
8
+ * @description Проверяет на наличие в строке символов разных регистров
9
+ * @example
10
+ * ```ts
11
+ * const validate = string(containsDifferentCases());
12
+ * validate('testTEST');
13
+ * ```
14
+ */
15
+ export declare const containsDifferentCases: <TLastSchemaValues extends Record<string, unknown>>(params?: ContainsDifferentCasesParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
16
+ export {};
@@ -0,0 +1,22 @@
1
+ import { createRule } from '../core';
2
+ import { CONTAINS_DIFFERENT_CASES_ERROR_CODE } from './constants';
3
+ /**
4
+ * @description Проверяет на наличие в строке символов разных регистров
5
+ * @example
6
+ * ```ts
7
+ * const validate = string(containsDifferentCases());
8
+ * validate('testTEST');
9
+ * ```
10
+ */
11
+ export const containsDifferentCases = (params) => createRule((value, ctx) => {
12
+ const containsLowerCaseRegex = /(?=.*[A-ZА-ЯЁ])/;
13
+ const containsUpperCaseRegex = /(?=.*[a-zа-яё])/;
14
+ if (!containsLowerCaseRegex.test(value) ||
15
+ !containsUpperCaseRegex.test(value)) {
16
+ return ctx.createError({
17
+ code: CONTAINS_DIFFERENT_CASES_ERROR_CODE,
18
+ message: (params === null || params === void 0 ? void 0 : params.message) || 'Строка должна содержать символы разного регистра',
19
+ });
20
+ }
21
+ return undefined;
22
+ });
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsDifferentCases';
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsDifferentCases';
@@ -0,0 +1,2 @@
1
+ import { ErrorCode } from '../core';
2
+ export declare const CONTAINS_NUMBERS_ERROR_CODE: ErrorCode;
@@ -0,0 +1,2 @@
1
+ import { createErrorCode } from '../core';
2
+ export const CONTAINS_NUMBERS_ERROR_CODE = createErrorCode('containsNumbers');
@@ -0,0 +1,16 @@
1
+ type ContainsNumbersParams = {
2
+ /**
3
+ * @description Замена стандартного сообщения ошибки.
4
+ */
5
+ message?: string;
6
+ };
7
+ /**
8
+ * @description Проверяет на наличие чисел в строке
9
+ * @example
10
+ * ```ts
11
+ * const validate = string(containsNumbers());
12
+ * validate('test123');
13
+ * ```
14
+ */
15
+ export declare const containsNumbers: <TLastSchemaValues extends Record<string, unknown>>(params?: ContainsNumbersParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
16
+ export {};
@@ -0,0 +1,20 @@
1
+ import { createRule } from '../core';
2
+ import { CONTAINS_NUMBERS_ERROR_CODE } from './constants';
3
+ /**
4
+ * @description Проверяет на наличие чисел в строке
5
+ * @example
6
+ * ```ts
7
+ * const validate = string(containsNumbers());
8
+ * validate('test123');
9
+ * ```
10
+ */
11
+ export const containsNumbers = (params) => createRule((value, ctx) => {
12
+ const containsNumbersRegex = /\d/;
13
+ if (!containsNumbersRegex.test(value)) {
14
+ return ctx.createError({
15
+ code: CONTAINS_NUMBERS_ERROR_CODE,
16
+ message: (params === null || params === void 0 ? void 0 : params.message) || 'Строка должна содержать числа',
17
+ });
18
+ }
19
+ return undefined;
20
+ });
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsNumbers';
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsNumbers';
@@ -0,0 +1,2 @@
1
+ import { ErrorCode } from '../core';
2
+ export declare const CONTAINS_PUNCTUATION_MARKS_ERROR_CODE: ErrorCode;
@@ -0,0 +1,2 @@
1
+ import { createErrorCode } from '../core';
2
+ export const CONTAINS_PUNCTUATION_MARKS_ERROR_CODE = createErrorCode('containsPunctuationMarks');
@@ -0,0 +1,16 @@
1
+ type ContainsPunctuationMarksParams = {
2
+ /**
3
+ * @description Замена стандартного сообщения ошибки.
4
+ */
5
+ message?: string;
6
+ };
7
+ /**
8
+ * @description Проверяет на наличие в строке знаков пунктуации !$%&’()+,-./:;<=>?@[]^_{|}”
9
+ * @example
10
+ * ```ts
11
+ * const validate = string(containsPunctuationMarks());
12
+ * validate('test?');
13
+ * ```
14
+ */
15
+ export declare const containsPunctuationMarks: <TLastSchemaValues extends Record<string, unknown>>(params?: ContainsPunctuationMarksParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
16
+ export {};
@@ -0,0 +1,20 @@
1
+ import { createRule } from '../core';
2
+ import { CONTAINS_PUNCTUATION_MARKS_ERROR_CODE } from './constants';
3
+ /**
4
+ * @description Проверяет на наличие в строке знаков пунктуации !$%&’()+,-./:;<=>?@[]^_{|}”
5
+ * @example
6
+ * ```ts
7
+ * const validate = string(containsPunctuationMarks());
8
+ * validate('test?');
9
+ * ```
10
+ */
11
+ export const containsPunctuationMarks = (params) => createRule((value, ctx) => {
12
+ const containsPunctuationMarksRegex = /(?=.*[!$%&’”'"()+,-.\/:;<=>?@\[\]^_{|}])/;
13
+ if (!containsPunctuationMarksRegex.test(value)) {
14
+ return ctx.createError({
15
+ code: CONTAINS_PUNCTUATION_MARKS_ERROR_CODE,
16
+ message: (params === null || params === void 0 ? void 0 : params.message) || 'Строка должна содержать знаки пунктуации',
17
+ });
18
+ }
19
+ return undefined;
20
+ });
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsPunctuationMarks';
@@ -0,0 +1,2 @@
1
+ export * from './constants';
2
+ export * from './containsPunctuationMarks';
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { object, objectAsync, OBJECT_TYPE_ERROR_INFO, type Schema, type SchemaValue, type ObjectGuard, type ObjectAsyncGuard, } from './object';
2
- export { optional } from './optional';
2
+ export { optional, optionalAsync } from './optional';
3
3
  export { string, STRING_TYPE_ERROR_INFO, stringAsync } from './string';
4
4
  export { date, INVALID_DATE_ERROR_INFO, DATE_TYPE_ERROR_INFO } from './date';
5
5
  export { number, NAN_NUMBER_ERROR_INFO, NUMBER_TYPE_ERROR_INFO, INFINITY_NUMBER_ERROR_INFO, } from './number';
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { object, objectAsync, OBJECT_TYPE_ERROR_INFO, } from './object';
2
- export { optional } from './optional';
2
+ export { optional, optionalAsync } from './optional';
3
3
  export { string, STRING_TYPE_ERROR_INFO, stringAsync } from './string';
4
4
  export { date, INVALID_DATE_ERROR_INFO, DATE_TYPE_ERROR_INFO } from './date';
5
5
  export { number, NAN_NUMBER_ERROR_INFO, NUMBER_TYPE_ERROR_INFO, INFINITY_NUMBER_ERROR_INFO, } from './number';
@@ -1 +1,2 @@
1
1
  export * from './optional';
2
+ export * from './optionalAsync';
package/optional/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export * from './optional';
2
+ export * from './optionalAsync';
@@ -0,0 +1 @@
1
+ export * from './optionalAsync';
@@ -0,0 +1 @@
1
+ export * from './optionalAsync';
@@ -0,0 +1,6 @@
1
+ import { AsyncIndependentValidationRule, AsyncValidationRule } from '../../core';
2
+ /**
3
+ * @description Выключает проверку на required в guard. Предназначен для асинхронных правил.
4
+ * @example object({ name: optionalAsync(stringAsync(min(22))) })
5
+ */
6
+ export declare const optionalAsync: <TLastSchemaValues extends Record<string, unknown>>(rule: AsyncValidationRule<unknown, TLastSchemaValues>) => AsyncIndependentValidationRule<unknown, TLastSchemaValues>;
@@ -0,0 +1,18 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { callAsyncRule, createContext, } from '../../core';
11
+ // TODO: необходимо добавить возможность использовать вложенные guards
12
+ /**
13
+ * @description Выключает проверку на required в guard. Предназначен для асинхронных правил.
14
+ * @example object({ name: optionalAsync(stringAsync(min(22))) })
15
+ */
16
+ export const optionalAsync = (rule) => (value, ctx) => __awaiter(void 0, void 0, void 0, function* () {
17
+ return callAsyncRule(rule, value, createContext(ctx, value, { isOptional: true }));
18
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astral/validations",
3
- "version": "4.8.0",
3
+ "version": "4.9.0",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {