@diia-inhouse/validators 3.0.0 → 4.0.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.
@@ -10,7 +10,7 @@ interface BasicRule<T extends RuleType> {
10
10
  type: T;
11
11
  optional?: boolean;
12
12
  default?: unknown;
13
- null?: boolean;
13
+ nullable?: boolean;
14
14
  }
15
15
  interface Sanitazible {
16
16
  convert?: boolean;
@@ -25,7 +25,7 @@ export interface NumberRule extends BasicRule<"number">, Sanitazible {
25
25
  negative?: boolean;
26
26
  }
27
27
  export interface ArrayRule<T = null> extends BasicRule<"array"> {
28
- items?: ValidationProperty<T>;
28
+ items?: ValidationProperty<T> | CommonRule;
29
29
  empty?: boolean;
30
30
  min?: number;
31
31
  max?: number;
@@ -78,7 +78,8 @@ export interface ObjectIdRule extends BasicRule<"objectId">, Sanitazible {}
78
78
  export interface BooleanRule extends BasicRule<"boolean">, Sanitazible {}
79
79
  type CommonRule = BasicRule<"any" | "forbidden"> | EnumRule;
80
80
  type ComplexRule = StringRule | NumberRule | BooleanRule | ArrayRule | ObjectRule | DateRule | CustomDateRule | EmailRule | EnumRule | ObjectIdRule | RecordRule<string, unknown> | VersionRule;
81
- type ValidationProperty<T = null> = T extends null ? ValidationRule : T extends string ? StringRule | EmailRule | VersionRule | BasicRule<"uuid" | "phoneNumber" | "internationalPhoneNumber"> : T extends number ? NumberRule : T extends boolean ? BooleanRule : T extends Date ? DateRule | CustomDateRule | StringRule : T extends Buffer ? BasicRule<"buffer"> : T extends ObjectId ? ObjectIdRule | StringRule : T extends ArrayLike<infer U> ? ArrayRule<U> : T extends object ? ObjectRule<T> | RecordRule<keyof T, Required<T>[keyof T]> : ValidationRule;
81
+ type ValidationProperty<T = null> = PropertyRule<Exclude<T, null | undefined>>;
82
+ type PropertyRule<T> = [T] extends [never] ? ValidationRule : T extends string ? StringRule | EmailRule | VersionRule | BasicRule<"uuid" | "phoneNumber" | "internationalPhoneNumber"> : T extends number ? NumberRule : T extends boolean ? BooleanRule : T extends Date ? DateRule | CustomDateRule | StringRule : T extends Buffer ? BasicRule<"buffer"> : T extends ObjectId ? ObjectIdRule | StringRule : T extends ArrayLike<infer U> ? ArrayRule<U> : T extends object ? ObjectRule<T> | RecordRule<keyof T, Required<T>[keyof T]> : ValidationRule;
82
83
  type Rule = string | boolean | ComplexRule | CommonRule | BasicRule<Exclude<RuleType, CommonRule["type"] | ComplexRule["type"]>>;
83
84
  export type ValidationRule<T = null> = T extends null ? Rule : T extends ArrayLike<infer U> ? ArrayRule<U> : T extends object ? ObjectRule<T> : Rule;
84
85
  export type ValidationSchema<T = null> = T extends null ? {
@@ -1,10 +1,8 @@
1
1
  // src/rules/date.ts
2
2
  /**
3
- * `customDate` rule: a string containing a `DD.MM.YYYY` date.
3
+ * `customDate` rule: a `DD.MM.YYYY` string that is an existing calendar date.
4
4
  *
5
- * The default pattern is not anchored and does not check day/month ranges.
6
- * With `convert: true` the value is replaced with a `Date` at UTC midnight; out-of-range parts roll over,
7
- * e.g. `32.13.2024` becomes 2025-02-01.
5
+ * With `convert: true` the value is replaced with a `Date` at UTC midnight.
8
6
  *
9
7
  * @example
10
8
  * { birthDate: { type: 'customDate', convert: true } }
@@ -12,9 +10,9 @@
12
10
  var DateValidationRule = class {
13
11
  checkPattern;
14
12
  /**
15
- * @param checkPattern - Pattern the string must match.
13
+ * @param checkPattern - Pattern the string must match before it is split by `.` into day, month and year.
16
14
  */
17
- constructor(checkPattern = /(?:\d{2}\.){2}\d{4}/) {
15
+ constructor(checkPattern = /^(?:\d{2}\.){2}\d{4}$/) {
18
16
  this.checkPattern = checkPattern;
19
17
  }
20
18
  getName() {
@@ -28,37 +26,24 @@ var DateValidationRule = class {
28
26
  * Signature: function(value, field, parent, errors, context)
29
27
  */
30
28
  return ({ schema, messages }) => {
31
- let sanitized = false;
32
- const src = [`
33
- if (typeof value !== 'string' || !${this.checkPattern.toString()}.test(value)) {
29
+ const sanitized = schema.convert === true;
30
+ return {
31
+ sanitized,
32
+ source: `
33
+ var parts = typeof value === 'string' && ${this.checkPattern.toString()}.test(value) ? value.split('.') : null;
34
+ var date = parts && new Date(Date.UTC(+parts[2], parts[1] - 1, +parts[0]));
35
+ if (!date || date.getUTCFullYear() !== +parts[2] || date.getUTCMonth() !== parts[1] - 1 || date.getUTCDate() !== +parts[0]) {
34
36
  ${validator.makeError({
35
- type: "customDate",
36
- actual: "value",
37
- messages
38
- })}
39
- }
40
- `];
41
- if (schema.convert === true) {
42
- sanitized = true;
43
- src.push(`
44
- var origValue = value;
45
- if (!(value instanceof Date)) {
46
- var parts = origValue.split('.');
47
- value = new Date(Date.UTC(parts[2], parts[1] - 1, parts[0]));
48
- if (isNaN(value)) {
49
- ${validator.makeError({
50
37
  type: "customDate",
51
- actual: "origValue",
38
+ actual: "value",
52
39
  messages
53
40
  })}
54
- }
55
- }
56
- `);
57
- }
58
- src.push("return value;");
59
- return {
60
- sanitized,
61
- source: src.join("\n")
41
+ return value;
42
+ }
43
+
44
+ ${sanitized ? "value = date;" : ""}
45
+ return value;
46
+ `
62
47
  };
63
48
  };
64
49
  }
@@ -9,10 +9,7 @@ export declare const phoneNumberValidation: ParameterValidation;
9
9
  export declare const phoneNumberWithoutPlusValidation: ParameterValidation;
10
10
  /** Email address with a top-level domain of 2 to 64 letters. */
11
11
  export declare const emailValidation: ParameterValidation;
12
- /**
13
- * Email address like {@link emailValidation} whose top-level domain does not start with `ru` or `su`.
14
- * This also rejects unrelated domains such as `.run` or `.surf`.
15
- */
12
+ /** Email address like {@link emailValidation} whose top-level domain is not `ru` or `su`. */
16
13
  export declare const emailRuValidation: ParameterValidation;
17
14
  /**
18
15
  * Builds a pagination schema with optional `skip` and `limit`, both converted to numbers.
@@ -19,19 +19,18 @@ const availableMobileCodes = [
19
19
  "97",
20
20
  "98",
21
21
  "99",
22
- "75",
23
- "77,"
22
+ "75"
24
23
  ];
25
24
  /** Ukrainian mobile number in the `+380XXXXXXXXX` format. */
26
25
  const phoneNumberValidation = {
27
26
  regexp: String.raw`^\+380(${availableMobileCodes.join("|")})\d{7}$`,
28
- flags: ["i", "g"],
27
+ flags: ["i"],
29
28
  errorMessage: "Упс, ви ввели неправильний номер телефону. Використовуйте формат + 38 (0ХХ) ХХХ ХХ ХХ."
30
29
  };
31
30
  /** Ukrainian mobile number in the `380XXXXXXXXX` format, without `+`. */
32
31
  const phoneNumberWithoutPlusValidation = {
33
32
  regexp: String.raw`^380(${availableMobileCodes.join("|")})\d{7}$`,
34
- flags: ["i", "g"],
33
+ flags: ["i"],
35
34
  errorMessage: "Упс, ви ввели неправильний номер телефону. Використовуйте формат 38 (0ХХ) ХХХ ХХ ХХ."
36
35
  };
37
36
  /** Email address with a top-level domain of 2 to 64 letters. */
@@ -40,12 +39,9 @@ const emailValidation = {
40
39
  flags: ["i"],
41
40
  errorMessage: "Упс, ви ввели неправильний email. Виправте дані або спробуйте іншу пошту."
42
41
  };
43
- /**
44
- * Email address like {@link emailValidation} whose top-level domain does not start with `ru` or `su`.
45
- * This also rejects unrelated domains such as `.run` or `.surf`.
46
- */
42
+ /** Email address like {@link emailValidation} whose top-level domain is not `ru` or `su`. */
47
43
  const emailRuValidation = {
48
- regexp: String.raw`^([a-zA-Z0-9_%+-]{1,}\.){0,}[a-zA-Z0-9_%+-]{1,}@([a-zA-Z0-9_%+-]{1,}\.){1,}(?!ru|su)[A-Za-z]{2,64}$`,
44
+ regexp: String.raw`^([a-zA-Z0-9_%+-]{1,}\.){0,}[a-zA-Z0-9_%+-]{1,}@([a-zA-Z0-9_%+-]{1,}\.){1,}(?!(?:ru|su)$)[A-Za-z]{2,64}$`,
49
45
  flags: ["i"],
50
46
  errorMessage: "Йой, це ж електронна адреса з російським доменом. Ми не можемо її прийняти. Спробуйте іншу скриньку, будь ласка."
51
47
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diia-inhouse/validators",
3
- "version": "3.0.0",
3
+ "version": "4.0.1",
4
4
  "description": "Data validators package",
5
5
  "license": "SEE LICENCE IN LICENCE.md",
6
6
  "author": "diia-team",