validno 0.2.6 → 0.3.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 (49) hide show
  1. package/dist/Schema.js +6 -5
  2. package/dist/ValidnoResult.js +12 -7
  3. package/dist/checkType.js +1 -0
  4. package/dist/constants/details.js +11 -11
  5. package/dist/constants/schema.js +10 -10
  6. package/dist/dev.js +67 -27
  7. package/dist/engine/ValidateEngine.js +44 -0
  8. package/dist/engine/ValidnoResult.js +102 -0
  9. package/dist/engine/index.js +2 -0
  10. package/dist/engine/methods/finishValidation.js +15 -0
  11. package/dist/engine/methods/handleKey.js +41 -0
  12. package/dist/engine/methods/handleMissingKey.js +19 -0
  13. package/dist/engine/methods/handleMissingKeyValidation.js +9 -0
  14. package/dist/engine/methods/handleNestedKey.js +19 -0
  15. package/dist/engine/methods/validate.js +14 -0
  16. package/dist/engine/methods/validateRules.js +172 -0
  17. package/dist/engine/methods/validateType.js +134 -0
  18. package/dist/types/common.js +1 -0
  19. package/dist/utils/errors.js +30 -21
  20. package/dist/utils/helpers.js +55 -57
  21. package/dist/utils/validateType.js +9 -8
  22. package/dist/utils/validations.js +157 -153
  23. package/dist/validate/index.js +1 -0
  24. package/dist/validate/validate.js +151 -0
  25. package/dist/validate.js +136 -127
  26. package/dist/validateEngine/ValidateEngine.js +44 -0
  27. package/dist/validateEngine/index.js +2 -0
  28. package/dist/validateEngine/methods/ValidateEngine.js +139 -0
  29. package/dist/validateEngine/methods/checkRulesForKey.js +15 -0
  30. package/dist/validateEngine/methods/checkValueType.js +134 -0
  31. package/dist/validateEngine/methods/finalizeValidation.js +15 -0
  32. package/dist/validateEngine/methods/finishValidation.js +15 -0
  33. package/dist/validateEngine/methods/handleKey.js +43 -0
  34. package/dist/validateEngine/methods/handleMissingKey.js +19 -0
  35. package/dist/validateEngine/methods/handleMissingKeyValidation.js +9 -0
  36. package/dist/validateEngine/methods/handleNestedKey.js +19 -0
  37. package/dist/validateEngine/methods/validate.js +14 -0
  38. package/dist/validateEngine/methods/validateKey.js +31 -0
  39. package/dist/validateEngine/methods/validateKeyDetails.js +13 -0
  40. package/dist/validateEngine/methods/validateKeyValue.js +13 -0
  41. package/dist/validateEngine/methods/validateNestedKey.js +19 -0
  42. package/dist/validateEngine/methods/validateType.js +134 -0
  43. package/dist/validateEngine/validate.js +14 -0
  44. package/dist/validateSchema/ValidateEngine.js +147 -0
  45. package/dist/validateSchema/index.js +6 -0
  46. package/dist/validateSchema/validate.js +151 -0
  47. package/dist/validateSchema.js +6 -0
  48. package/dist/validateType.js +4 -4
  49. package/package.json +1 -1
package/dist/Schema.js CHANGED
@@ -1,14 +1,15 @@
1
- import { ESchemaFields } from "./constants/schema.js";
2
- import validate from "./validate.js";
3
- export const defaultSchemaKeys = Object.values(ESchemaFields);
1
+ import { SchemaFields } from "./constants/schema.js";
2
+ import ValidateEngine from "./engine/ValidateEngine.js";
3
+ export const defaultSchemaKeys = Object.values(SchemaFields);
4
4
  export class Schema {
5
5
  constructor(inputSchemaDefinition) {
6
6
  if (!inputSchemaDefinition || typeof inputSchemaDefinition !== 'object') {
7
7
  throw new Error("Invalid schema input");
8
8
  }
9
- this.schema = inputSchemaDefinition;
9
+ this.definition = inputSchemaDefinition;
10
10
  }
11
11
  validate(inputData, validationKeys) {
12
- return validate.call(this, inputData, validationKeys);
12
+ const engine = new ValidateEngine(this.definition);
13
+ return engine.validate(inputData, validationKeys);
13
14
  }
14
15
  }
@@ -17,12 +17,14 @@ class ValidnoResult {
17
17
  this.byKeys[key] = result;
18
18
  }
19
19
  fixParentByChilds(parentKey, childChecks = []) {
20
- const isEveryOk = childChecks.every(c => c === true);
20
+ const isEveryOk = childChecks.every(check => check === true);
21
21
  this.setKeyStatus(parentKey, isEveryOk);
22
- if (isEveryOk === true)
22
+ if (isEveryOk) {
23
23
  this.setPassed(parentKey);
24
- else
24
+ }
25
+ else {
25
26
  this.setFailed(parentKey);
27
+ }
26
28
  }
27
29
  setMissing(key, errMsg) {
28
30
  const error = errMsg || _errors.getMissingError(key);
@@ -35,7 +37,7 @@ class ValidnoResult {
35
37
  this.setKeyStatus(key, true);
36
38
  }
37
39
  setFailed(key, msg) {
38
- if (key in this.errorsByKeys === false) {
40
+ if (!(key in this.errorsByKeys)) {
39
41
  this.errorsByKeys[key] = [];
40
42
  }
41
43
  this.failed.push(key);
@@ -55,8 +57,9 @@ class ValidnoResult {
55
57
  this.passed = [...this.passed, ...resultsNew.passed];
56
58
  this.byKeys = Object.assign(Object.assign({}, this.byKeys), resultsNew.byKeys);
57
59
  for (const key in resultsNew.errorsByKeys) {
58
- if (key in this.errorsByKeys === false)
60
+ if (!(key in this.errorsByKeys)) {
59
61
  this.errorsByKeys[key] = [];
62
+ }
60
63
  this.errorsByKeys[key] = [
61
64
  ...this.errorsByKeys[key],
62
65
  ...resultsNew.errorsByKeys[key]
@@ -72,10 +75,12 @@ class ValidnoResult {
72
75
  }
73
76
  }
74
77
  finish() {
75
- if (this.failed.length || this.errors.length)
78
+ if (this.failed.length || this.errors.length) {
76
79
  this.ok = false;
77
- else
80
+ }
81
+ else {
78
82
  this.ok = true;
83
+ }
79
84
  this.clearEmptyErrorsByKeys();
80
85
  return this;
81
86
  }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -1,11 +1,11 @@
1
- export var EValidationId;
2
- (function (EValidationId) {
3
- EValidationId["Missing"] = "missing";
4
- EValidationId["Type"] = "type";
5
- EValidationId["Rule"] = "rule";
6
- })(EValidationId || (EValidationId = {}));
7
- export var EValidationDetails;
8
- (function (EValidationDetails) {
9
- EValidationDetails["OK"] = "ok";
10
- EValidationDetails["INVALID_DATE"] = "\u0414\u0430\u0442\u0430 \u043D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
11
- })(EValidationDetails || (EValidationDetails = {}));
1
+ export var ValidationIds;
2
+ (function (ValidationIds) {
3
+ ValidationIds["Missing"] = "missing";
4
+ ValidationIds["Type"] = "type";
5
+ ValidationIds["Rule"] = "rule";
6
+ })(ValidationIds || (ValidationIds = {}));
7
+ export var ValidationDetails;
8
+ (function (ValidationDetails) {
9
+ ValidationDetails["OK"] = "OK";
10
+ ValidationDetails["INVALID_DATE"] = "Invalid date";
11
+ })(ValidationDetails || (ValidationDetails = {}));
@@ -1,10 +1,10 @@
1
- export var ESchemaFields;
2
- (function (ESchemaFields) {
3
- ESchemaFields["Required"] = "required";
4
- ESchemaFields["Type"] = "type";
5
- ESchemaFields["EachType"] = "eachType";
6
- ESchemaFields["Rules"] = "rules";
7
- ESchemaFields["Title"] = "title";
8
- ESchemaFields["CustomMessage"] = "customMessage";
9
- ESchemaFields["JoinErrors"] = "joinErrors";
10
- })(ESchemaFields || (ESchemaFields = {}));
1
+ export var SchemaFields;
2
+ (function (SchemaFields) {
3
+ SchemaFields["Required"] = "required";
4
+ SchemaFields["Type"] = "type";
5
+ SchemaFields["EachType"] = "eachType";
6
+ SchemaFields["Rules"] = "rules";
7
+ SchemaFields["Title"] = "title";
8
+ SchemaFields["CustomMessage"] = "customMessage";
9
+ SchemaFields["JoinErrors"] = "joinErrors";
10
+ })(SchemaFields || (SchemaFields = {}));
package/dist/dev.js CHANGED
@@ -1,30 +1,70 @@
1
- import { Schema } from "./Schema.js";
2
- const testSchema = new Schema({
3
- parent: {
4
- collection: {
5
- type: [String, Array],
6
- required: true
1
+ import Schema from './index.js';
2
+ const schema = new Schema({
3
+ name: {
4
+ type: String,
5
+ required: true
6
+ },
7
+ lastVisit: {
8
+ type: Date,
9
+ required: true,
10
+ },
11
+ age: {
12
+ type: Number,
13
+ required: true,
14
+ },
15
+ email: {
16
+ type: String,
17
+ required: true,
18
+ rules: {
19
+ isEmail: true
7
20
  }
8
- }
21
+ },
22
+ isAwesome: {
23
+ type: Boolean,
24
+ required: true
25
+ },
26
+ friends: {
27
+ type: Array,
28
+ required: true,
29
+ eachType: String,
30
+ },
31
+ broRegex: {
32
+ type: RegExp,
33
+ required: true,
34
+ },
35
+ socials: {
36
+ x: {
37
+ type: String,
38
+ required: false
39
+ },
40
+ instagram: {
41
+ type: String,
42
+ required: false
43
+ }
44
+ },
45
+ nullableField: {
46
+ type: null,
47
+ required: false,
48
+ },
9
49
  });
10
- const testObj = {
11
- parent: {
12
- collection: ['xxxx']
13
- }
14
- };
15
- const testObj2 = {
16
- parent: {
17
- collection: false
18
- }
19
- };
20
- const testObj3 = {
21
- parent: {
22
- collection: 'str'
23
- }
50
+ const exampleObj = {
51
+ name: 'Barney Stinson',
52
+ age: 35,
53
+ lastVisit: new Date('2025-05-05'),
54
+ email: 'legggen@dary.com',
55
+ isAwesome: true,
56
+ friends: [
57
+ 'Ted Mosby',
58
+ 'Marshall Eriksen',
59
+ 'Lily Aldrin',
60
+ 'Robin Scherbatsky'
61
+ ],
62
+ socials: {
63
+ x: '@barney_stinson',
64
+ insstagram: '@barney_stinson'
65
+ },
66
+ broRegex: /bro/i,
67
+ deletedAt: null,
24
68
  };
25
- const res = testSchema.validate(testObj);
26
- console.log(res.ok === true ? '#1 ✅' : '#1 ❌');
27
- const res2 = testSchema.validate(testObj2);
28
- console.log(res2.ok === false ? '#2 ✅' : '#2 ❌');
29
- const res3 = testSchema.validate(testObj3);
30
- console.log(res3.ok === true ? '#3 ✅' : '#3 ❌');
69
+ const validation = schema.validate(exampleObj);
70
+ console.log(validation);
@@ -0,0 +1,44 @@
1
+ import ValidnoResult from "./ValidnoResult.js";
2
+ import validate from "./methods/validate.js";
3
+ import validateType from "./methods/validateType.js";
4
+ import validateRules from "./methods/validateRules.js";
5
+ import handleMissingKey from "./methods/handleMissingKey.js";
6
+ import handleNestedKey from "./methods/handleNestedKey.js";
7
+ import handleKey from "./methods/handleKey.js";
8
+ import handleMissingKeyValidation from "./methods/handleMissingKeyValidation.js";
9
+ import finishValidation from "./methods/finishValidation.js";
10
+ class ValidateEngine {
11
+ constructor(definition) {
12
+ this.definition = definition;
13
+ this.result = new ValidnoResult();
14
+ }
15
+ validate(data, validationKeys) {
16
+ return validate.call(this, data, validationKeys);
17
+ }
18
+ handleKey(input) {
19
+ return handleKey.call(this, input);
20
+ }
21
+ handleNestedKey(input) {
22
+ return handleNestedKey.call(this, input);
23
+ }
24
+ handleMissingKey(schema, input) {
25
+ return handleMissingKey(schema, input);
26
+ }
27
+ handleMissingNestedKey(nestedKey, results) {
28
+ results.setMissing(nestedKey);
29
+ return results;
30
+ }
31
+ handleMissingKeyValidation(params) {
32
+ return handleMissingKeyValidation.call(this, params);
33
+ }
34
+ validateType(input) {
35
+ return validateType(input);
36
+ }
37
+ validateRules(input) {
38
+ return validateRules.call(this, input);
39
+ }
40
+ finishValidation(checks) {
41
+ return finishValidation(checks);
42
+ }
43
+ }
44
+ export default ValidateEngine;
@@ -0,0 +1,102 @@
1
+ import _errors from "../utils/errors.js";
2
+ class ValidnoResult {
3
+ constructor(results) {
4
+ this.ok = (results === null || results === void 0 ? void 0 : results.ok) !== undefined ? results.ok : null;
5
+ this.missed = (results === null || results === void 0 ? void 0 : results.missed) || [];
6
+ this.failed = (results === null || results === void 0 ? void 0 : results.failed) || [];
7
+ this.passed = (results === null || results === void 0 ? void 0 : results.passed) || [];
8
+ this.errors = (results === null || results === void 0 ? void 0 : results.errors) || [];
9
+ this.byKeys = (results === null || results === void 0 ? void 0 : results.byKeys) || {};
10
+ this.errorsByKeys = (results === null || results === void 0 ? void 0 : results.errorsByKeys) || {};
11
+ }
12
+ setNoData(key) {
13
+ this.ok = false;
14
+ this.errors = [`Missing value for '${key}'`];
15
+ }
16
+ setKeyStatus(key, result) {
17
+ this.byKeys[key] = result;
18
+ }
19
+ fixParentByChilds(parentKey, childChecks = []) {
20
+ const isEveryOk = childChecks.every(check => check === true);
21
+ this.setKeyStatus(parentKey, isEveryOk);
22
+ if (isEveryOk) {
23
+ this.setPassed(parentKey);
24
+ }
25
+ else {
26
+ this.setFailed(parentKey);
27
+ }
28
+ }
29
+ setMissing(key, errMsg) {
30
+ const error = errMsg || _errors.getMissingError(key);
31
+ this.missed.push(key);
32
+ this.setFailed(key, error);
33
+ this.setKeyStatus(key, false);
34
+ }
35
+ setPassed(key) {
36
+ this.passed.push(key);
37
+ this.setKeyStatus(key, true);
38
+ }
39
+ setFailed(key, msg) {
40
+ if (!(key in this.errorsByKeys)) {
41
+ this.errorsByKeys[key] = [];
42
+ }
43
+ this.failed.push(key);
44
+ this.setKeyStatus(key, false);
45
+ if (!msg)
46
+ return;
47
+ this.errors.push(msg);
48
+ this.errorsByKeys[key].push(msg);
49
+ }
50
+ joinErrors(separator = '; ') {
51
+ return _errors.joinErrors(this.errors, separator);
52
+ }
53
+ merge(resultsNew) {
54
+ this.failed = [...this.failed, ...resultsNew.failed];
55
+ this.errors = [...this.errors, ...resultsNew.errors];
56
+ this.missed = [...this.missed, ...resultsNew.missed];
57
+ this.passed = [...this.passed, ...resultsNew.passed];
58
+ this.byKeys = Object.assign(Object.assign({}, this.byKeys), resultsNew.byKeys);
59
+ for (const key in resultsNew.errorsByKeys) {
60
+ if (!(key in this.errorsByKeys)) {
61
+ this.errorsByKeys[key] = [];
62
+ }
63
+ this.errorsByKeys[key] = [
64
+ ...this.errorsByKeys[key],
65
+ ...resultsNew.errorsByKeys[key]
66
+ ];
67
+ }
68
+ return this;
69
+ }
70
+ clearEmptyErrorsByKeys() {
71
+ for (const key in this.errorsByKeys) {
72
+ if (!this.errorsByKeys[key].length) {
73
+ delete this.errorsByKeys[key];
74
+ }
75
+ }
76
+ }
77
+ finish() {
78
+ if (this.failed.length || this.errors.length) {
79
+ this.ok = false;
80
+ }
81
+ else {
82
+ this.ok = true;
83
+ }
84
+ this.clearEmptyErrorsByKeys();
85
+ return this;
86
+ }
87
+ data() {
88
+ return {
89
+ ok: this.ok,
90
+ missed: this.missed,
91
+ failed: this.failed,
92
+ passed: this.passed,
93
+ errors: this.errors,
94
+ byKeys: this.byKeys,
95
+ errorsByKeys: this.errorsByKeys,
96
+ };
97
+ }
98
+ isValid() {
99
+ return this.ok === true;
100
+ }
101
+ }
102
+ export default ValidnoResult;
@@ -0,0 +1,2 @@
1
+ import ValidateEngine from "./ValidateEngine.js";
2
+ export default ValidateEngine;
@@ -0,0 +1,15 @@
1
+ function finishValidation(checks) {
2
+ const { results, nestedKey, missedCheck, typeChecked, rulesChecked } = checks;
3
+ if (missedCheck.length)
4
+ results.setMissing(nestedKey);
5
+ const isPassed = !typeChecked.length && !rulesChecked.length && !missedCheck.length;
6
+ if (!isPassed) {
7
+ results.setFailed(nestedKey);
8
+ results.errorsByKeys[nestedKey] = [...results.errors];
9
+ }
10
+ else {
11
+ results.setPassed(nestedKey);
12
+ }
13
+ return results.finish();
14
+ }
15
+ export default finishValidation;
@@ -0,0 +1,41 @@
1
+ import _helpers from "../../utils/helpers.js";
2
+ import ValidnoResult from "../ValidnoResult.js";
3
+ function validateKeyValue(params) {
4
+ const { results, key, nestedKey, data, reqs, hasMissing } = params;
5
+ const missedCheck = [];
6
+ const typeChecked = [];
7
+ const rulesChecked = [];
8
+ if (hasMissing) {
9
+ return this.handleMissingKeyValidation({ results, key, nestedKey, data, reqs, missedCheck });
10
+ }
11
+ this.validateType({ results, key, value: data[key], reqs, nestedKey, typeChecked });
12
+ this.validateRules({ results, nestedKey, value: data[key], reqs, data, rulesChecked });
13
+ return this.finishValidation({ results, nestedKey, missedCheck, typeChecked, rulesChecked });
14
+ }
15
+ function validateKey(input) {
16
+ let { results, key, nestedKey, data, reqs } = input;
17
+ if (data === undefined) {
18
+ const noDataResult = new ValidnoResult();
19
+ noDataResult.setNoData(nestedKey);
20
+ }
21
+ if (!results)
22
+ results = new ValidnoResult();
23
+ if (!nestedKey)
24
+ nestedKey = key;
25
+ const hasMissing = _helpers.hasMissing(input);
26
+ if (_helpers.checkNestedIsMissing(reqs, data)) {
27
+ return this.handleMissingNestedKey(nestedKey, results);
28
+ }
29
+ if (_helpers.checkIsNested(reqs)) {
30
+ return this.handleNestedKey({ results, key, data, reqs, nestedKey });
31
+ }
32
+ return validateKeyValue.call(this, {
33
+ results,
34
+ key,
35
+ nestedKey,
36
+ data,
37
+ reqs,
38
+ hasMissing,
39
+ });
40
+ }
41
+ export default validateKey;
@@ -0,0 +1,19 @@
1
+ import { ValidationIds } from "../../constants/details.js";
2
+ import _errors from "../../utils/errors.js";
3
+ function handleMissingKey(schema, input) {
4
+ const { key, nestedKey, data, reqs } = input;
5
+ const messageKey = nestedKey || key;
6
+ const messageTitle = reqs.title || messageKey;
7
+ if (!reqs.customMessage)
8
+ return _errors.getMissingError(messageKey);
9
+ const errorMessage = reqs.customMessage({
10
+ keyword: ValidationIds.Missing,
11
+ value: data[key],
12
+ key: messageKey,
13
+ title: messageTitle,
14
+ reqs,
15
+ schema,
16
+ });
17
+ return errorMessage;
18
+ }
19
+ export default handleMissingKey;
@@ -0,0 +1,9 @@
1
+ function handleMissingKeyValidation(params) {
2
+ const schema = this.definition;
3
+ const { results, key, nestedKey, data, reqs, missedCheck } = params;
4
+ const errMsg = this.handleMissingKey(schema, { key, nestedKey, data, reqs });
5
+ missedCheck.push(false);
6
+ results.setMissing(nestedKey, errMsg);
7
+ return results;
8
+ }
9
+ export default handleMissingKeyValidation;
@@ -0,0 +1,19 @@
1
+ function handleNestedKey(input) {
2
+ const { results, key, nestedKey, data, reqs } = input;
3
+ const nestedKeys = Object.keys(reqs);
4
+ const nestedResults = [];
5
+ for (const itemKey of nestedKeys) {
6
+ const deepParams = {
7
+ key: itemKey,
8
+ data: data[key],
9
+ reqs: reqs[itemKey],
10
+ nestedKey: `${nestedKey}.${itemKey}`
11
+ };
12
+ const deepResults = this.handleKey(deepParams);
13
+ nestedResults.push(deepResults.ok);
14
+ results.merge(deepResults);
15
+ }
16
+ results.fixParentByChilds(nestedKey, nestedResults);
17
+ return results;
18
+ }
19
+ export default handleNestedKey;
@@ -0,0 +1,14 @@
1
+ import _helpers from "../../utils/helpers.js";
2
+ function validate(data, validationKeys) {
3
+ const hasKeysToCheck = _helpers.areKeysLimited(validationKeys);
4
+ const schemaKeys = Object.entries(this.definition);
5
+ for (const [key, reqs] of schemaKeys) {
6
+ const toBeValidated = _helpers.needValidation(key, hasKeysToCheck, validationKeys);
7
+ if (!toBeValidated)
8
+ continue;
9
+ const keyResult = this.handleKey({ key, data, reqs });
10
+ this.result.merge(keyResult);
11
+ }
12
+ return this.result.finish();
13
+ }
14
+ export default validate;
@@ -0,0 +1,172 @@
1
+ import _validations from "../../utils/validations.js";
2
+ export const rulesParams = {
3
+ lengthMin: {
4
+ allowedTypes: [String]
5
+ }
6
+ };
7
+ const ensureRuleHasCorrectType = (value, allowedTypes) => {
8
+ const isInAllowedList = allowedTypes.some(TYPE => {
9
+ const getType = (el) => Object.prototype.toString.call(el);
10
+ return getType(new TYPE()) == getType(value);
11
+ });
12
+ return isInAllowedList;
13
+ };
14
+ const rulesFunctions = {
15
+ custom: (key, val, func, extra) => {
16
+ return func(val, extra);
17
+ },
18
+ isEmail: (key, val) => {
19
+ return {
20
+ result: _validations.isEmail(val),
21
+ details: `Value must be a valid email address`
22
+ };
23
+ },
24
+ is: (key, val, equalTo) => {
25
+ return {
26
+ result: _validations.is(val, equalTo),
27
+ details: `Value must be equal to "${equalTo}"`
28
+ };
29
+ },
30
+ isNot: (key, val, notEqualTo) => {
31
+ return {
32
+ result: _validations.isNot(val, notEqualTo),
33
+ details: `Value must not be equal to "${notEqualTo}"`
34
+ };
35
+ },
36
+ min: (key, val, min) => {
37
+ return {
38
+ result: _validations.isNumberGte(val, min),
39
+ details: `Value must be greater than or equal to ${min}`
40
+ };
41
+ },
42
+ max: (key, val, max) => {
43
+ return {
44
+ result: _validations.isNumberLte(val, max),
45
+ details: `Value must be less than or equal to ${max}`
46
+ };
47
+ },
48
+ minMax: (key, val, minMax) => {
49
+ const [min, max] = minMax;
50
+ return {
51
+ result: _validations.isNumberGte(val, min) && _validations.isNumberLte(val, max),
52
+ details: `Value must be between ${min} and ${max}`
53
+ };
54
+ },
55
+ length: (key, val, length) => {
56
+ return {
57
+ result: _validations.lengthIs(val, length),
58
+ details: `Value must be equal to ${length}`
59
+ };
60
+ },
61
+ lengthNot: (key, val, lengthNot) => {
62
+ return {
63
+ result: _validations.lengthNot(val, lengthNot),
64
+ details: `Value must not be equal to ${lengthNot}`
65
+ };
66
+ },
67
+ lengthMinMax: (key, val, minMax) => {
68
+ const [min, max] = minMax;
69
+ return {
70
+ result: _validations.lengthMin(val, min) && _validations.lengthMax(val, max),
71
+ details: `Value must be between ${min} and ${max} characters`
72
+ };
73
+ },
74
+ lengthMin: (key, val, min) => {
75
+ ensureRuleHasCorrectType(val, rulesParams['lengthMin'].allowedTypes);
76
+ return {
77
+ result: _validations.lengthMin(val, min),
78
+ details: `Value must be at least ${min} characters`
79
+ };
80
+ },
81
+ lengthMax: (key, val, max) => {
82
+ return {
83
+ result: _validations.lengthMax(val, max),
84
+ details: `Value must not be exceed ${max} characters`
85
+ };
86
+ },
87
+ regex: (key, val, regex) => {
88
+ return {
89
+ result: _validations.regexTested(val, regex),
90
+ details: `Value must match the format ${regex}`
91
+ };
92
+ },
93
+ enum: (key, value, allowedList) => {
94
+ const output = {
95
+ result: true,
96
+ details: ''
97
+ };
98
+ if (!Array.isArray(value)) {
99
+ const isCorrect = allowedList.includes(value);
100
+ output.result = isCorrect,
101
+ output.details = isCorrect ? '' : `Value "${value}" is not allowed`;
102
+ }
103
+ else {
104
+ const incorrectValues = [];
105
+ value.forEach((v) => !allowedList.includes(v) ? incorrectValues.push(v) : {});
106
+ const isCorrect = incorrectValues.length === 0;
107
+ output.result = isCorrect,
108
+ output.details = isCorrect ? '' : `Values are not allowed: "${incorrectValues.join(', ')}"`;
109
+ }
110
+ return output;
111
+ }
112
+ };
113
+ function unnamed(key, value, requirements, inputObj) {
114
+ const result = {
115
+ ok: true,
116
+ details: []
117
+ };
118
+ if (requirements.required !== true && value === undefined)
119
+ return result;
120
+ if (!requirements || !requirements.rules || !Object.keys(requirements.rules).length) {
121
+ return result;
122
+ }
123
+ const rules = requirements.rules;
124
+ const title = requirements.title || key;
125
+ const allResults = [];
126
+ const allRulesKeys = Object.keys(rules);
127
+ let i = 0;
128
+ while (i < allRulesKeys.length) {
129
+ const ruleName = allRulesKeys[i];
130
+ if (ruleName in rulesFunctions === false) {
131
+ i++;
132
+ continue;
133
+ }
134
+ const func = rulesFunctions[ruleName];
135
+ const args = rules[ruleName];
136
+ const result = func(key, value, args, { schema: this.schema, input: inputObj });
137
+ if (requirements.customMessage && typeof requirements.customMessage === 'function') {
138
+ result.details = requirements.customMessage({
139
+ keyword: ruleName,
140
+ value: value,
141
+ key: key,
142
+ title: title,
143
+ reqs: requirements,
144
+ schema: this.schema,
145
+ rules: rules,
146
+ });
147
+ }
148
+ allResults.push(result);
149
+ i++;
150
+ }
151
+ const failedResults = allResults.filter(el => el.result === false);
152
+ if (failedResults.length) {
153
+ result.ok = false;
154
+ result.details = failedResults.map(el => el.details);
155
+ }
156
+ return result;
157
+ }
158
+ ;
159
+ function validateRules(input) {
160
+ const { results, nestedKey, value, reqs, data, rulesChecked } = input;
161
+ const ruleCheck = unnamed.call(this, nestedKey, value, reqs, data);
162
+ if (!ruleCheck.ok) {
163
+ rulesChecked.push(false);
164
+ ruleCheck.details.forEach((el) => {
165
+ if (!(nestedKey in results.errorsByKeys))
166
+ results.errorsByKeys[nestedKey] = [];
167
+ results.errors.push(el);
168
+ results.errorsByKeys[nestedKey] = ['1'];
169
+ });
170
+ }
171
+ }
172
+ export default validateRules;