react-hook-form-rules 1.5.9 → 1.6.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.
Files changed (32) hide show
  1. package/.github/workflows/test.yml +17 -0
  2. package/CHANGELOG.md +29 -0
  3. package/i18n.ts +25 -0
  4. package/index.ts +4 -2
  5. package/jest.config.js +7 -0
  6. package/locales/en.json +12 -0
  7. package/locales/ru.json +11 -0
  8. package/package.json +7 -3
  9. package/rules/array/get-max-array-length-rule.ts +3 -3
  10. package/rules/array/get-min-array-length-rule.ts +4 -4
  11. package/rules/array/get-required-array-rule.ts +2 -2
  12. package/rules/array/tests/get-max-array-length-rule.test.ts +17 -0
  13. package/rules/array/tests/get-min-array-length-rule.test.ts +17 -0
  14. package/rules/array/tests/get-required-array-rule.test.ts +16 -0
  15. package/rules/default/get-max-length-rule.ts +8 -8
  16. package/rules/default/get-max-rule.ts +3 -1
  17. package/rules/default/get-min-length-rule.ts +3 -2
  18. package/rules/default/get-min-rule.ts +5 -1
  19. package/rules/default/get-require-rule.ts +2 -2
  20. package/rules/default/tests/get-max-length-rule.test.ts +24 -0
  21. package/rules/default/tests/get-max-rule.test.ts +24 -0
  22. package/rules/default/tests/get-min-length-rule.test.ts +24 -0
  23. package/rules/default/tests/get-min-rule.test.ts +24 -0
  24. package/rules/default/tests/get-required-rule.test.ts +10 -0
  25. package/rules/object/get-required-object-rule.ts +5 -5
  26. package/rules/object/tests/get-require-object-rule.test.ts +18 -0
  27. package/rules/{link → patterns}/get-email-rule.ts +7 -10
  28. package/rules/patterns/get-pattern-rule.ts +12 -0
  29. package/rules/{link → patterns}/get-url-rule.ts +6 -9
  30. package/rules/patterns/tests/get-email-rule.test.ts +27 -0
  31. package/rules/patterns/tests/get-pattern-rule.test.ts +10 -0
  32. package/rules/patterns/tests/get-url-rule.test.ts +28 -0
@@ -0,0 +1,17 @@
1
+ name: Unit Tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ - uses: actions/setup-node@v3
14
+ with:
15
+ node-version: 20
16
+ - run: npm ci
17
+ - run: npm run test
package/CHANGELOG.md CHANGED
@@ -1,3 +1,32 @@
1
+ ## [1.6.0](https://github.com/chopperqt/react-hook-form-rules/compare/v1.5.8...v1.6.0) (2025-03-16)
2
+
3
+ ### 🆕 Features
4
+
5
+ * добавлен CI для запуска тестов ([31146a6](https://github.com/chopperqt/react-hook-form-rules/commit/31146a64d76637d307181fbbbeca400bfc0a47a3))
6
+ * добавлен текст для getMaxArrayLengthRule ([bac2105](https://github.com/chopperqt/react-hook-form-rules/commit/bac2105c3958a7f85fcab6f9cebc902dd1ab4850))
7
+ * добавлен тест для getUrlRule ([c43710c](https://github.com/chopperqt/react-hook-form-rules/commit/c43710c869358bcf0a7fcae2a0948f3411d5f9f0))
8
+ * добавлена локализация ошибок en/ru ([3b0d373](https://github.com/chopperqt/react-hook-form-rules/commit/3b0d373d18ad32edf8e4d132d0e7b19499657aa0))
9
+ * добавление unit(jest) тестов ([5dfec8e](https://github.com/chopperqt/react-hook-form-rules/commit/5dfec8e8d9d34268c2a308fcd11e410fcede8d17))
10
+ * добавление локали ([b7a6c94](https://github.com/chopperqt/react-hook-form-rules/commit/b7a6c941453f0dfaa918d5fd8f0da1eeaa3e696b))
11
+ * добавление текстов для getMinRule и getRequiredRule ([313af6d](https://github.com/chopperqt/react-hook-form-rules/commit/313af6dab27f78c27ef4de5a4c3f73f3d9090786))
12
+ * добавление теста для getPatternRule ([ed891a8](https://github.com/chopperqt/react-hook-form-rules/commit/ed891a8e24b75dec6c011faf2ec884a43d1b01f8))
13
+ * добавление тестов для getMaxLengthRule ([db0ff06](https://github.com/chopperqt/react-hook-form-rules/commit/db0ff060495ff5d25e33135c7b6b3959afff961a))
14
+ * добавление тестов для getMaxRule ([b618a40](https://github.com/chopperqt/react-hook-form-rules/commit/b618a40be413912869cff0fae687d07bf6b76683))
15
+ * добавление тестов для getMinArrayLengthRule ([d6dab70](https://github.com/chopperqt/react-hook-form-rules/commit/d6dab7031c682d3f8827546b6da87afeb667a655))
16
+ * добавлено новое правило ([3debbcb](https://github.com/chopperqt/react-hook-form-rules/commit/3debbcb47eebcf08e4b8788d3c349808a4f0c258))
17
+ * добавлены тесты для getMinLengthRule ([385b798](https://github.com/chopperqt/react-hook-form-rules/commit/385b79874fb4da958caf9ac4d6575d49e7f88e3d))
18
+
19
+ ### 🐞 Bug Fixes
20
+
21
+ * добавлен перевод ошибок ([21b63d6](https://github.com/chopperqt/react-hook-form-rules/commit/21b63d65f96571b746918d20910debea90473849))
22
+
23
+ ### 🔥 Code Refactoring
24
+
25
+ * доработки конфига ([325f134](https://github.com/chopperqt/react-hook-form-rules/commit/325f134af712efd9159226b8f2778812467e7783))
26
+ * изменение архитектуры папок для тестов ([66d5d8a](https://github.com/chopperqt/react-hook-form-rules/commit/66d5d8a0b85e7df25d72aa5bfc14b54ff1179096))
27
+ * незначительные правки ([86c9616](https://github.com/chopperqt/react-hook-form-rules/commit/86c961681f10984c2da58e72c4a0be96539e264a))
28
+ * ренейминг папки ([21fae72](https://github.com/chopperqt/react-hook-form-rules/commit/21fae72f410c8a0b51ccfc3515dae3888dda213a))
29
+
1
30
  ## [1.5.9](https://github.com/chopperqt/react-hook-form-rules/compare/v1.5.8...v1.5.9) (2025-03-15)
2
31
 
3
32
  ### 🔥 Code Refactoring
package/i18n.ts ADDED
@@ -0,0 +1,25 @@
1
+ const translataions = {
2
+ en: require("./locales/en.json"),
3
+ ru: require("./locales/ru.json"),
4
+ };
5
+
6
+ let currentLang = 'en'
7
+
8
+ export const setLanguage = (lang: string) => {
9
+ if ((translataions as any)[lang]) {
10
+ currentLang = lang;
11
+ } else {
12
+ console.warn(`⚠️ Language "${lang}" is not supported. Defaulting to English.`);
13
+ }
14
+ }
15
+
16
+ export const translate = (key: string, params = {}) => {
17
+ let text = (translataions as any)[currentLang][key] || key;
18
+
19
+ // Подставляем параметры (например, {{min}})
20
+ Object.keys(params).forEach((param) => {
21
+ text = text.replace(`{{${param}}}`, (params as any)[param]);
22
+ });
23
+
24
+ return text;
25
+ }
package/index.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { getEmailRule } from "./rules/link/get-email-rule";
2
- import { getUrlRule } from "./rules/link/get-url-rule";
1
+ import { getEmailRule } from "./rules/patterns/get-email-rule";
2
+ import { getUrlRule } from "./rules/patterns/get-url-rule";
3
+ import { getPatternRule } from "./rules/patterns/get-pattern-rule";
3
4
 
4
5
  import { getMaxArrayLengthRule } from "./rules/array/get-max-array-length-rule";
5
6
  import { getMinArrayLengthRule } from "./rules/array/get-min-array-length-rule";
@@ -14,6 +15,7 @@ import { getRequiredRule } from "./rules/default/get-require-rule";
14
15
  import { getRequiredObjectRule } from "./rules/object/get-required-object-rule";
15
16
 
16
17
  export {
18
+ getPatternRule,
17
19
  getMaxRule,
18
20
  getRequiredObjectRule,
19
21
  getRequiredArrayRule,
package/jest.config.js ADDED
@@ -0,0 +1,7 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} **/
2
+ module.exports = {
3
+ testEnvironment: "node",
4
+ transform: {
5
+ "^.+\.tsx?$": ["ts-jest",{}],
6
+ },
7
+ };
@@ -0,0 +1,12 @@
1
+ {
2
+ "required": "This field is required.",
3
+ "maxArrayLength": "Maximum number of values - {{max}}.",
4
+ "minArrayLength": "Minimum number of values - {{min}}.",
5
+ "min": "Minimum value - {{min}}.",
6
+ "max": "Maximum value - {{max}}.",
7
+ "minLength": "Minimum length - {{min}}.",
8
+ "maxLength": "Maximum length - {{max}}.",
9
+ "email": "Please check the correctness of the entered email address.",
10
+ "url": "The URL does not match the format."
11
+ }
12
+
@@ -0,0 +1,11 @@
1
+ {
2
+ "required": "Поле объязательное.",
3
+ "maxArrayLength": "Максимальное количество значений - {{max}}.",
4
+ "minArrayLength": "Минимальное количество значений - {{min}}.",
5
+ "min": "Минимальное значение - {{min}}.",
6
+ "max": "Максимальное значение - {{max}}.",
7
+ "minLength": "Минимальная длина - {{min}}.",
8
+ "maxLength": "Максимальная длина - {{max}}.",
9
+ "email": "Проверьте правильность введенного адреса электронной почты.",
10
+ "url": "URL не соответствует формату."
11
+ }
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "react-hook-form-rules",
3
- "version": "1.5.9",
3
+ "version": "1.6.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1",
8
+ "test": "jest",
9
+ "test-watch": "jest --watch --verbose",
9
10
  "build": "tsc --declaration",
10
11
  "check-npmrc": "cat ~/.npmrc",
11
12
  "deploy": "npm run build && npm publish",
@@ -22,9 +23,12 @@
22
23
  "@semantic-release/changelog": "^6.0.3",
23
24
  "@semantic-release/exec": "^7.0.3",
24
25
  "@semantic-release/git": "^10.0.1",
26
+ "@types/jest": "^29.5.14",
25
27
  "conventional-changelog-conventionalcommits": "^8.0.0",
26
28
  "cz-conventional-changelog": "^3.3.0",
27
- "semantic-release": "^24.2.3"
29
+ "jest": "^29.7.0",
30
+ "semantic-release": "^24.2.3",
31
+ "ts-jest": "^29.2.6"
28
32
  },
29
33
  "config": {
30
34
  "commitizen": {
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n";
2
+
1
3
  /**
2
4
  * Validates an array for the maximum number of values.
3
5
  * @param arr - Array of values.
@@ -11,9 +13,7 @@ export const getMaxArrayLengthRule = (
11
13
  maxLength: number,
12
14
  message?: string,
13
15
  ) => {
14
- const defaultMessage = `Maximum number of values - ${maxLength}.`;
15
-
16
- const formattedMessage = message || defaultMessage;
16
+ const formattedMessage = message || translate('maxArrayLength', { max: maxLength });
17
17
 
18
18
  return arr.length < maxLength || formattedMessage;
19
19
  };
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n";
2
+
1
3
  /**
2
4
  * Validates an array for the maximum number of values.
3
5
  * @param arr - Array of values.
@@ -11,9 +13,7 @@ export const getMinArrayLengthRule = (
11
13
  minLength: number,
12
14
  message?: string,
13
15
  ) => {
14
- const defaultMessage = `Minimum number of values - ${minLength}.`;
15
-
16
- const formattedMessage = message || defaultMessage;
16
+ const formattedMessage = message || translate('minArrayLength', { min: minLength });
17
17
 
18
- return arr.length > minLength || formattedMessage;
18
+ return arr.length >= minLength || formattedMessage;
19
19
  };
@@ -1,4 +1,4 @@
1
- import { REQUIRED_MESSAGE_TEXT } from "../constants";
1
+ import { translate } from "../../i18n";
2
2
 
3
3
  /**
4
4
  * Validates an array, checking if it contains values.
@@ -8,5 +8,5 @@ import { REQUIRED_MESSAGE_TEXT } from "../constants";
8
8
  * @example rules: { validate: (arr) => getRequiredArrayRule(arr) }
9
9
  */
10
10
  export const getRequiredArrayRule = (arr: unknown[], message?: string) => {
11
- return arr.length > 0 || (message || REQUIRED_MESSAGE_TEXT);
11
+ return arr.length > 0 || (message || translate('required'));
12
12
  };
@@ -0,0 +1,17 @@
1
+ import { getMaxArrayLengthRule } from '../get-max-array-length-rule'
2
+
3
+ const MAX_LENGTH = 2;
4
+
5
+ describe('Тестирование функции getMaxArrayLengthRule', () => {
6
+ test('Проверка, что функция возвращает текстовое сообщение с ошибкой если длинна массива превышает максимальную.', () => {
7
+ expect(getMaxArrayLengthRule([1, 2, 3], MAX_LENGTH)).toBe(`Maximum number of values - ${MAX_LENGTH}.`)
8
+ })
9
+
10
+ test('Проверка, что функция возвращает true, если длинна массива меньше, либо равна максимальной.', () => {
11
+ expect(getMaxArrayLengthRule([1], MAX_LENGTH)).toBe(true)
12
+ })
13
+
14
+ test('Проверка, что функция возвращает кастомное сообщение, если кол-во заначений превышает максимальное.', () => {
15
+ expect(getMaxArrayLengthRule([1, 2, 3, 4], MAX_LENGTH, 'test message')).toBe('test message')
16
+ })
17
+ })
@@ -0,0 +1,17 @@
1
+ import { getMinArrayLengthRule } from "../get-min-array-length-rule";
2
+
3
+ const MIN_LENGTH = 2;
4
+
5
+ describe('Тестирование функции getMinArrayLengthRule', () => {
6
+ test('Проверка, что функция возвращает текстовое сообщение с ошибкой если длинна массива меньше минимальной.', () => {
7
+ expect(getMinArrayLengthRule([1], MIN_LENGTH)).toBe(`Minimum number of values - ${MIN_LENGTH}.`)
8
+ })
9
+
10
+ test('Проверка, что функция возвращает true, если длинна массива большe, либо равна минимальной.', () => {
11
+ expect(getMinArrayLengthRule([1, 3, 4], MIN_LENGTH)).toBe(true)
12
+ })
13
+
14
+ test('Проверка, что функция возвращает кастомное сообщение, если кол-во заначений меньше минимальной.', () => {
15
+ expect(getMinArrayLengthRule([1], MIN_LENGTH, 'test message')).toBe('test message')
16
+ })
17
+ })
@@ -0,0 +1,16 @@
1
+ import { REQUIRED_MESSAGE_TEXT } from '../../constants'
2
+ import { getRequiredArrayRule } from '../get-required-array-rule'
3
+
4
+ describe('Тестирование функции getRequiredArrayRule', () => {
5
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой, когда массив не содержит значения.', () => {
6
+ expect(getRequiredArrayRule([], 'test message')).toBe('test message')
7
+ })
8
+
9
+ test('Проверка, что функция возвращает true, когда массив не пустой.', () => {
10
+ expect(getRequiredArrayRule([1, 2, 3])).toBe(true)
11
+ })
12
+
13
+ test('Проверка, что функция возвращает базовое сообщение, когда массив пустой.', () => {
14
+ expect(getRequiredArrayRule([])).toBe(REQUIRED_MESSAGE_TEXT)
15
+ })
16
+ })
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n";
2
+
1
3
  /**
2
4
  * Validates the maximum length of a string.
3
5
  * @param maxLength - Maximum number of characters allowed.
@@ -5,11 +7,9 @@
5
7
  *
6
8
  * @example rules: { maxLength: getMaxLengthRule(1000) }
7
9
  */
8
- export const getMaxLengthRule = (maxLength: number, message?: string) => {
9
- const formattedMessage = `Maximum length - ${maxLength}.`;
10
-
11
- return {
12
- value: maxLength,
13
- message: message || formattedMessage,
14
- };
15
- };
10
+ export const getMaxLengthRule = (maxLength: number, message?: string) => ({
11
+ value: maxLength,
12
+ message: message || translate('maxLength', {
13
+ max: maxLength,
14
+ }),
15
+ })
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n";
2
+
1
3
  /**
2
4
  * Returns an error if the number exceeds the specified value.
3
5
  * @param max - Maximum number.
@@ -7,5 +9,5 @@
7
9
  */
8
10
  export const getMaxRule = (max: number, message?: string) => ({
9
11
  value: max,
10
- message: message || `Maximum value - ${max}.`,
12
+ message: message || translate('max', { max }),
11
13
  });
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n";
2
+
1
3
  /**
2
4
  * Returns a rule that validates the minimum length of a string.
3
5
  * @param minLength - Minimum number of characters allowed.
@@ -6,10 +8,9 @@
6
8
  * @example rules: { minLength: getMinLengthRule(20) }
7
9
  */
8
10
  export const getMinLengthRule = (minLength: number, message?: string) => {
9
- const formattedMessage = `Minimum length - ${minLength}.`;
10
11
 
11
12
  return {
12
13
  value: minLength,
13
- message: message || formattedMessage,
14
+ message: message || translate('minLength', { min: minLength }),
14
15
  };
15
16
  };
@@ -1,3 +1,5 @@
1
+ import { translate } from "../../i18n"
2
+
1
3
  /**
2
4
  * Returns an error if the number is less than the specified value.
3
5
  * @param min - Minimum number.
@@ -7,5 +9,7 @@
7
9
  */
8
10
  export const getMinRule = (min: number, message?: string) => ({
9
11
  value: min,
10
- message: message || `Minimum value - ${min}.`,
12
+ message: message || translate('min', {
13
+ min,
14
+ }),
11
15
  })
@@ -1,4 +1,4 @@
1
- import { REQUIRED_MESSAGE_TEXT } from "../constants";
1
+ import { translate } from "../../i18n";
2
2
 
3
3
  /**
4
4
  * Validates a required field.
@@ -9,7 +9,7 @@ import { REQUIRED_MESSAGE_TEXT } from "../constants";
9
9
  */
10
10
  export const getRequiredRule = (
11
11
  isRequired = true,
12
- message = REQUIRED_MESSAGE_TEXT
12
+ message = translate('required')
13
13
  ) => ({
14
14
  value: isRequired,
15
15
  message,
@@ -0,0 +1,24 @@
1
+ import { getMaxLengthRule } from "../get-max-length-rule"
2
+
3
+ describe('Тестирование функции getMinLengthRule', () => {
4
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой.', () => {
5
+ expect(getMaxLengthRule(1, 'test message')).toEqual({
6
+ value: 1,
7
+ message: 'test message',
8
+ })
9
+ })
10
+
11
+ test('Проверка, что функция возвращает базовую ошибку.', () => {
12
+ expect(getMaxLengthRule(1)).toEqual({
13
+ value: 1,
14
+ message: `Maximum length - ${1}.`
15
+ })
16
+ })
17
+
18
+ test('Проверка, что функция возвращает базовую ошибку и переданное минимальное значение.', () => {
19
+ expect(getMaxLengthRule(111)).toEqual({
20
+ value: 111,
21
+ message: `Maximum length - 111.`
22
+ })
23
+ })
24
+ })
@@ -0,0 +1,24 @@
1
+ import { getMaxRule } from "../get-max-rule"
2
+
3
+ describe('Тестирование функции getMaxRule', () => {
4
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой.', () => {
5
+ expect(getMaxRule(1, 'test message')).toEqual({
6
+ value: 1,
7
+ message: 'test message',
8
+ })
9
+ })
10
+
11
+ test('Проверка, что функция возвращает базовую ошибку.', () => {
12
+ expect(getMaxRule(1)).toEqual({
13
+ value: 1,
14
+ message: `Maximum value - 1.`
15
+ })
16
+ })
17
+
18
+ test('Проверка, что функция возвращает базовую ошибку и переданное минимальное значение.', () => {
19
+ expect(getMaxRule(111)).toEqual({
20
+ value: 111,
21
+ message: `Maximum value - 111.`
22
+ })
23
+ })
24
+ })
@@ -0,0 +1,24 @@
1
+ import { getMinLengthRule } from "../get-min-length-rule"
2
+
3
+ describe('Тестирование функции getMinLengthRule', () => {
4
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой.', () => {
5
+ expect(getMinLengthRule(1, 'test message')).toEqual({
6
+ value: 1,
7
+ message: 'test message',
8
+ })
9
+ })
10
+
11
+ test('Проверка, что функция возвращает базовую ошибку.', () => {
12
+ expect(getMinLengthRule(1)).toEqual({
13
+ value: 1,
14
+ message: `Minimum length - ${1}.`
15
+ })
16
+ })
17
+
18
+ test('Проверка, что функция возвращает базовую ошибку и переданное минимальное значение.', () => {
19
+ expect(getMinLengthRule(111)).toEqual({
20
+ value: 111,
21
+ message: `Minimum length - 111.`
22
+ })
23
+ })
24
+ })
@@ -0,0 +1,24 @@
1
+ import { getMinRule } from "../get-min-rule";
2
+
3
+ describe('Тестирование функции getMinRule', () => {
4
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой.', () => {
5
+ expect(getMinRule(1, 'test message')).toEqual({
6
+ value: 1,
7
+ message: 'test message',
8
+ })
9
+ })
10
+
11
+ test('Проверка, что функция возвращает базовую ошибку.', () => {
12
+ expect(getMinRule(1)).toEqual({
13
+ value: 1,
14
+ message: `Minimum value - 1.`
15
+ })
16
+ })
17
+
18
+ test('Проверка, что функция возвращает базовую ошибку и переданное минимальное значение.', () => {
19
+ expect(getMinRule(111)).toEqual({
20
+ value: 111,
21
+ message: `Minimum value - 111.`
22
+ })
23
+ })
24
+ })
@@ -0,0 +1,10 @@
1
+ import { getRequiredRule } from '../get-require-rule'
2
+
3
+ describe('Тестирование функции getRequiredRule', () => {
4
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой.', () => {
5
+ expect(getRequiredRule(true, 'test message')).toEqual({
6
+ value: true,
7
+ message: 'test message',
8
+ })
9
+ })
10
+ })
@@ -1,20 +1,20 @@
1
- import { REQUIRED_MESSAGE_TEXT } from "../constants";
1
+ import { translate } from "../../i18n";
2
2
 
3
3
  /**
4
4
  * Validates an object, checking if it contains values.
5
- * @param obj - Object with values.
6
- * @param message - Custom message.
5
+ * @param {Object} obj - Object with values.
6
+ * @param {string} message - Custom message.
7
7
  *
8
8
  * @example rules: { validate: (obj) => getRequiredObjectRule(obj) }
9
9
  */
10
10
  export const getRequiredObjectRule = (obj: Record<string, unknown>, message?: string) => {
11
- const formattedMessage = message || REQUIRED_MESSAGE_TEXT;
11
+ const formattedMessage = message || translate("required");
12
12
 
13
13
  if (!obj) {
14
14
  return false || formattedMessage;
15
15
  }
16
16
 
17
- const isEmpty = Object?.keys(obj)?.length === 0;
17
+ const isEmpty = Object?.keys(obj)?.length > 0;
18
18
 
19
19
  return isEmpty || formattedMessage;
20
20
  };
@@ -0,0 +1,18 @@
1
+ import { REQUIRED_MESSAGE_TEXT } from '../../constants'
2
+ import { getRequiredObjectRule } from '../get-required-object-rule'
3
+
4
+ describe('Тестирование функции getRequireObjectRule', () => {
5
+ test('Проверка, что функция возвращает кастомное сообщение с ошибкой, когда объект не содержит значения.', () => {
6
+ expect(getRequiredObjectRule({}, 'test message')).toBe('test message')
7
+ })
8
+
9
+ test('Проверка, что функция возвращает true, когда объект не пустой.', () => {
10
+ expect(getRequiredObjectRule({ test: '123' })).toBe(true)
11
+ })
12
+
13
+ test('Проверка, что функция возвращает базовое сообщение, когда объект пустой.', () => {
14
+ expect(getRequiredObjectRule({})).toBe(REQUIRED_MESSAGE_TEXT)
15
+ })
16
+ })
17
+
18
+
@@ -1,5 +1,7 @@
1
+ import { getPatternRule } from "./get-pattern-rule";
2
+ import { translate } from "../../i18n";
3
+
1
4
  const DEFAULT_PATTERN = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
2
- const DEFAULT_MESSAGE = "Please check the correctness of the entered email address.";
3
5
 
4
6
  interface EmailRule {
5
7
  pattern?: RegExp;
@@ -9,17 +11,12 @@ interface EmailRule {
9
11
  /**
10
12
  * Validates an email address.
11
13
  * @param options - Parameters.
12
- * @param options.pattern - Regular expression.
13
- * @param options.message - Custom message.
14
+ * @param {string} options.pattern - Regular expression.
15
+ * @param {string} options.message - Custom message.
14
16
  *
15
17
  * @example rules: { pattern: getEmailRule() }
16
18
  */
17
19
  export const getEmailRule = ({
18
20
  pattern = DEFAULT_PATTERN,
19
- message = DEFAULT_MESSAGE,
20
- }: EmailRule) => {
21
- return {
22
- value: pattern,
23
- message,
24
- };
25
- };
21
+ message = translate('email'),
22
+ }: EmailRule) => getPatternRule(pattern, message)
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Returns a rule that validates the pattern.
3
+ * @param options - Parameters.
4
+ * @param options.pattern - Regular expression.
5
+ * @param options.message - Custom message.
6
+ *
7
+ * @example rules: { pattern: getPatternRule(pattern) }
8
+ */
9
+ export const getPatternRule = (pattern: RegExp, message: string) => ({
10
+ value: pattern,
11
+ message,
12
+ })
@@ -1,4 +1,6 @@
1
- const DEFAULT_MESSAGE = "The URL does not match the format.";
1
+ import { translate } from "../../i18n";
2
+ import { getPatternRule } from "./get-pattern-rule";
3
+
2
4
  const DEFAULT_PATTERN =
3
5
  /(http(s)?):\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
4
6
 
@@ -13,14 +15,9 @@ interface UrlRule {
13
15
  * @param options.pattern - Regular expression.
14
16
  * @param options.message - Custom message.
15
17
  *
16
- * @example rules: { pattern: getUrlValidationRule() }
18
+ * @example rules: { pattern: getUrlRule() }
17
19
  */
18
20
  export const getUrlRule = ({
19
21
  pattern = DEFAULT_PATTERN,
20
- message = DEFAULT_MESSAGE,
21
- }: UrlRule) => {
22
- return {
23
- message,
24
- value: pattern,
25
- };
26
- };
22
+ message = translate('url'),
23
+ }: UrlRule) => getPatternRule(pattern, message)
@@ -0,0 +1,27 @@
1
+ import { getEmailRule } from "../get-email-rule";
2
+
3
+ const DEFAULT_MESSAGE = "Please check the correctness of the entered email address.";
4
+ const DEFAULT_PATTERN = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
5
+
6
+ describe('Тестирование функции getEmailRule', () => {
7
+ test('Проверка значения по умолчанию', () => {
8
+ expect(getEmailRule({})).toEqual({
9
+ message: DEFAULT_MESSAGE,
10
+ value: DEFAULT_PATTERN
11
+ });
12
+ });
13
+
14
+ test('Проверка передачи кастомного сообщения', () => {
15
+ expect(getEmailRule({ message: 'Custom message' })).toEqual({
16
+ message: 'Custom message',
17
+ value: DEFAULT_PATTERN
18
+ });
19
+ })
20
+
21
+ test('Проверка передачи камсного паттерна', () => {
22
+ expect(getEmailRule({ pattern: /test/ })).toEqual({
23
+ message: DEFAULT_MESSAGE,
24
+ value: /test/
25
+ });
26
+ })
27
+ })
@@ -0,0 +1,10 @@
1
+ import { getPatternRule } from "../get-pattern-rule";
2
+
3
+ describe('Тестирование функции getEmailRule', () => {
4
+ test('Проверка кастомного сообщения', () => {
5
+ expect(getPatternRule(/-/, 'test message')).toEqual({
6
+ message: 'test message',
7
+ value: /-/
8
+ });
9
+ });
10
+ })
@@ -0,0 +1,28 @@
1
+ import { getUrlRule } from "../get-url-rule";
2
+
3
+ const DEFAULT_MESSAGE = "The URL does not match the format.";
4
+ const DEFAULT_PATTERN =
5
+ /(http(s)?):\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
6
+
7
+ describe('Тестирование функции getEmailRule', () => {
8
+ test('Проверка значения по умолчанию', () => {
9
+ expect(getUrlRule({})).toEqual({
10
+ message: DEFAULT_MESSAGE,
11
+ value: DEFAULT_PATTERN
12
+ });
13
+ });
14
+
15
+ test('Проверка передачи кастомного сообщения', () => {
16
+ expect(getUrlRule({ message: 'Custom message' })).toEqual({
17
+ message: 'Custom message',
18
+ value: DEFAULT_PATTERN
19
+ });
20
+ })
21
+
22
+ test('Проверка передачи камсного паттерна', () => {
23
+ expect(getUrlRule({ pattern: /test/ })).toEqual({
24
+ message: DEFAULT_MESSAGE,
25
+ value: /test/
26
+ });
27
+ })
28
+ })