light-paradate 1.1.1 → 2.0.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
@@ -31,6 +31,7 @@ npm install light-paradate
31
31
  ```
32
32
  Or with Yarn:
33
33
  ```bash
34
+ const parentId = validField(req, 'parent_id', { numericality: { onlyInteger: true, greaterThan: 0 } });
34
35
  yarn add light-paradate
35
36
  ```
36
37
 
@@ -44,6 +45,7 @@ Extracts a field from `req.query` or `req.body`, then runs validations according
44
45
  example:
45
46
  ```js
46
47
  const uuid = validField(req, 'uuid', { minLength: 36 });
48
+ const id = validField(req, 'id', { match: /^[1-9]\d*$/ });
47
49
  const orderBy = validField(req, 'orderBy', { includedIn: ['name', 'email', 'status'] });
48
50
  const statuses = validField(req, 'statuses[]', { includedIn: ['invited', 'active'] });
49
51
  const firstName = validField(req, 'firstName', { minLength: 5 });
@@ -54,42 +56,51 @@ const firstName = validField(req, 'firstName', { minLength: 5 });
54
56
  - `fieldName`: The field name to retrieve from `req.query` or `req.body`.
55
57
  - `options`: An optional object containing validation requirements.
56
58
  Possible values for the `options` argument include:
59
+ - `optional`: boolean - Allows the field to be omitted even when other validators such as `minLength` are configured.
57
60
  - `required`: boolean - Indicates whether the field must have a non-empty value.
58
61
  - `minLength`: number - Specifies the minimum length the field value should have.
59
62
  - `maxLength`: number - Specifies the maximum length the field value can have.
63
+ - `match`: RegExp - Validates the field value against a regular expression.
64
+ - `numericality`: boolean | object - Converts the field to a number and validates numeric constraints. Supported object keys: `onlyInteger`, `greaterThan`, `greaterThanOrEqualTo`, `lessThan`, `lessThanOrEqualTo`.
60
65
  - `includedIn`: string[] - An array of valid strings that the field value must match to pass validation.
61
66
 
62
67
  #### Return Value
63
- - If valid, returns the string or string array (in case of fields that use `[]` notation).
64
- - Returns `undefined` if the field is not required and not present.
68
+ - If valid, returns the string, number, string array, or number array (in case of fields that use `[]` notation).
69
+ - Returns `undefined` if the field is not required and not present, or if `optional: true` is set and the field is omitted.
65
70
  - Throws an error if validation fails.
66
71
 
67
72
  #### Behavior
68
- - Check presence: If `options.required` is set or if `options.minLength` is defined, the field must be present or an error will be thrown.
73
+ - Check presence: If `options.required` is set or if `options.minLength` is defined, the field must be present unless `optional: true` is set.
69
74
  - Check length: If `options.minLength` is set, throws an error if the field’s value is shorter than the specified length.
75
+ - Check pattern: If `options.match` is defined, throws an error if the field’s value does not match the provided regular expression.
76
+ - Check numericality: If `options.numericality` is defined, converts the field to a number and throws an error if it is not numeric or does not satisfy the configured numeric constraints.
70
77
  - Check inclusion: If `options.includedIn` is defined, throws an error if the field’s value (or values) are not in the specified list.
71
78
 
72
79
  Array fields: If your field name ends with `[]` (e.g., `statuses[]`), the utility will treat the field as an Array. If there is only one value, it will be returned in a single-element array.
73
80
 
74
81
  ### validEmail
75
82
 
76
- `validEmail(req)`
83
+ `validEmail(req, options)`
77
84
 
78
85
  Extracts and validates the "email" field from `req.query` or `req.body`, ensuring it is both present and syntactically valid.
79
86
 
80
87
  example:
81
88
  ```js
82
89
  const email = validEmail(req);
90
+ const alternateEmail = validEmail(req, { optional: true });
83
91
  ```
84
92
  #### Parameters
85
93
  - `req`: A request-like object with query and body.
94
+ - `options`: Optional configuration.
95
+ - `optional`: boolean - Allows `email` to be omitted. If present, it is still validated.
86
96
 
87
97
  #### Return Value
88
98
  - Returns a valid email string if validation passes.
89
- - Throws an error if the email is missing or invalid.
99
+ - Returns `undefined` if `optional: true` is set and the email is missing.
100
+ - Throws an error if the email is invalid, or if it is missing without `optional: true`.
90
101
 
91
102
  #### Behavior
92
- - Checks presence: Throws an error `emailRequired` if the field `email` is not found in either `req.query` or `req.body`.
103
+ - Checks presence: Throws an error `emailRequired` if the field `email` is not found in either `req.query` or `req.body`, unless `optional: true` is set.
93
104
  - Checks format: Uses the `email-validator` package under the hood to ensure the format is correct. If invalid, throws an error `emailInvalid`.
94
105
 
95
106
  #### License
@@ -1,9 +1,19 @@
1
1
  interface OptionsType {
2
2
  includedIn?: string[];
3
+ match?: RegExp;
3
4
  minLength?: number;
4
5
  maxLength?: number;
6
+ numericality?: boolean | NumericalityOptionsType;
7
+ optional?: boolean;
5
8
  required?: boolean;
6
9
  }
10
+ interface NumericalityOptionsType {
11
+ onlyInteger?: boolean;
12
+ greaterThan?: number;
13
+ greaterThanOrEqualTo?: number;
14
+ lessThan?: number;
15
+ lessThanOrEqualTo?: number;
16
+ }
7
17
  interface RequestType {
8
18
  query: {
9
19
  [key: string]: any;
@@ -12,6 +22,6 @@ interface RequestType {
12
22
  [key: string]: any;
13
23
  };
14
24
  }
15
- export declare const validField: (req: RequestType, fieldName: string, options: OptionsType) => string | string[] | undefined;
16
- export declare const validEmail: (req: RequestType) => string | undefined;
25
+ export declare const validField: (req: RequestType, fieldName: string, options: OptionsType) => string | string[] | number | number[] | undefined;
26
+ export declare const validEmail: (req: RequestType, options?: Pick<OptionsType, "optional">) => string | undefined;
17
27
  export {};
package/dist/cjs/index.js CHANGED
@@ -5,33 +5,78 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.validField = exports.validEmail = void 0;
7
7
  var _emailValidator = require("email-validator");
8
- /* eslint-disable @typescript-eslint/no-explicit-any */
9
-
10
- /* eslint-enable */
11
-
8
+ var formatFieldNameForError = function formatFieldNameForError(fieldName) {
9
+ var hasArraySuffix = fieldName.endsWith('[]');
10
+ var normalizedFieldName = hasArraySuffix ? fieldName.slice(0, -2) : fieldName;
11
+ var camelizedFieldName = normalizedFieldName.replace(/[_-]+([a-zA-Z0-9])/g, function (_, _char) {
12
+ return _char.toUpperCase();
13
+ });
14
+ return hasArraySuffix ? "".concat(camelizedFieldName, "[]") : camelizedFieldName;
15
+ };
16
+ var fieldError = function fieldError(fieldName, errorSuffix) {
17
+ return "".concat(formatFieldNameForError(fieldName)).concat(errorSuffix);
18
+ };
12
19
  var validateRequired = function validateRequired(options, fieldName) {
13
- if (options.required || options.minLength) throw new Error("".concat(fieldName, "Required"));
20
+ if (options.optional) return;
21
+ if (options.required || options.minLength) throw new Error(fieldError(fieldName, 'Required'));
14
22
  };
15
23
  var validateLength = function validateLength(fieldValue, fieldName, minLength, maxLength) {
16
24
  if (!minLength && !maxLength) return;
17
- if (minLength && fieldValue.length < minLength) throw new Error("".concat(fieldName, "TooShort"));
18
- if (maxLength && fieldValue.length > maxLength) throw new Error("".concat(fieldName, "TooLong"));
25
+ if (minLength && fieldValue.length < minLength) throw new Error(fieldError(fieldName, 'TooShort'));
26
+ if (maxLength && fieldValue.length > maxLength) throw new Error(fieldError(fieldName, 'TooLong'));
19
27
  };
20
- var validateInclusion = function validateInclusion(fieldValue, fieldName, includedIn) {
28
+ var validatePattern = function validatePattern(fieldValue, fieldName, pattern) {
29
+ if (!pattern) return;
30
+ if (!pattern.test(fieldValue)) throw new Error(fieldError(fieldName, 'IsInvalid'));
31
+ };
32
+ var validateNumericality = function validateNumericality(fieldValue, fieldName, numericality) {
33
+ if (!numericality) return fieldValue;
34
+ var numericValue = Number(fieldValue);
35
+ if (Number.isNaN(numericValue) || !Number.isFinite(numericValue)) {
36
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
37
+ }
38
+ if (numericality === true) return numericValue;
39
+ if (numericality.onlyInteger && !Number.isInteger(numericValue)) {
40
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
41
+ }
42
+ if (numericality.greaterThan !== undefined && numericValue <= numericality.greaterThan) {
43
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
44
+ }
45
+ if (numericality.greaterThanOrEqualTo !== undefined && numericValue < numericality.greaterThanOrEqualTo) {
46
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
47
+ }
48
+ if (numericality.lessThan !== undefined && numericValue >= numericality.lessThan) {
49
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
50
+ }
51
+ if (numericality.lessThanOrEqualTo !== undefined && numericValue > numericality.lessThanOrEqualTo) {
52
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
53
+ }
54
+ return numericValue;
55
+ };
56
+ var validateInclusion = function validateInclusion(fieldValue, fieldName, includedIn, pattern, numericality) {
21
57
  if (fieldName.endsWith('[]')) {
22
58
  // if the array has only 1 element, fieldValue is a string, not an array
23
59
  var arrayValue = fieldValue.constructor === Array ? fieldValue : [fieldValue];
24
60
  if (!arrayValue.every(function (value) {
25
61
  return includedIn === null || includedIn === void 0 ? void 0 : includedIn.includes(value);
26
62
  })) {
27
- throw new Error("".concat(fieldName, "IsInvalid"));
63
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
64
+ }
65
+ arrayValue.forEach(function (value) {
66
+ return validatePattern(value, fieldName, pattern);
67
+ });
68
+ if (numericality) {
69
+ return arrayValue.map(function (value) {
70
+ return validateNumericality(value, fieldName, numericality);
71
+ });
28
72
  }
29
73
  return arrayValue;
30
74
  } else {
31
75
  if (includedIn && !includedIn.includes(fieldValue)) {
32
- throw new Error("".concat(fieldName, "IsInvalid"));
76
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
33
77
  }
34
- return fieldValue;
78
+ validatePattern(fieldValue, fieldName, pattern);
79
+ return validateNumericality(fieldValue, fieldName, numericality);
35
80
  }
36
81
  };
37
82
  var validField = exports.validField = function validField(req, fieldName, options) {
@@ -43,12 +88,14 @@ var validField = exports.validField = function validField(req, fieldName, option
43
88
  return undefined;
44
89
  }
45
90
  validateLength(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.minLength, options === null || options === void 0 ? void 0 : options.maxLength);
46
- return validateInclusion(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.includedIn);
91
+ return validateInclusion(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.includedIn, options === null || options === void 0 ? void 0 : options.match, options === null || options === void 0 ? void 0 : options.numericality);
47
92
  };
48
93
  var validEmail = exports.validEmail = function validEmail(req) {
49
94
  var _req$body2;
95
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
50
96
  var email = req.query.email || ((_req$body2 = req.body) === null || _req$body2 === void 0 ? void 0 : _req$body2.email);
51
97
  if (!email) {
98
+ if (options.optional) return undefined;
52
99
  throw new Error('emailRequired');
53
100
  }
54
101
  if (!(0, _emailValidator.validate)(email)) {
package/dist/esm/index.js CHANGED
@@ -1,32 +1,76 @@
1
1
  import { validate as emailIsValid } from 'email-validator';
2
-
3
- /* eslint-disable @typescript-eslint/no-explicit-any */
4
-
5
- /* eslint-enable */
6
-
2
+ var formatFieldNameForError = function formatFieldNameForError(fieldName) {
3
+ var hasArraySuffix = fieldName.endsWith('[]');
4
+ var normalizedFieldName = hasArraySuffix ? fieldName.slice(0, -2) : fieldName;
5
+ var camelizedFieldName = normalizedFieldName.replace(/[_-]+([a-zA-Z0-9])/g, function (_, _char) {
6
+ return _char.toUpperCase();
7
+ });
8
+ return hasArraySuffix ? "".concat(camelizedFieldName, "[]") : camelizedFieldName;
9
+ };
10
+ var fieldError = function fieldError(fieldName, errorSuffix) {
11
+ return "".concat(formatFieldNameForError(fieldName)).concat(errorSuffix);
12
+ };
7
13
  var validateRequired = function validateRequired(options, fieldName) {
8
- if (options.required || options.minLength) throw new Error("".concat(fieldName, "Required"));
14
+ if (options.optional) return;
15
+ if (options.required || options.minLength) throw new Error(fieldError(fieldName, 'Required'));
9
16
  };
10
17
  var validateLength = function validateLength(fieldValue, fieldName, minLength, maxLength) {
11
18
  if (!minLength && !maxLength) return;
12
- if (minLength && fieldValue.length < minLength) throw new Error("".concat(fieldName, "TooShort"));
13
- if (maxLength && fieldValue.length > maxLength) throw new Error("".concat(fieldName, "TooLong"));
19
+ if (minLength && fieldValue.length < minLength) throw new Error(fieldError(fieldName, 'TooShort'));
20
+ if (maxLength && fieldValue.length > maxLength) throw new Error(fieldError(fieldName, 'TooLong'));
21
+ };
22
+ var validatePattern = function validatePattern(fieldValue, fieldName, pattern) {
23
+ if (!pattern) return;
24
+ if (!pattern.test(fieldValue)) throw new Error(fieldError(fieldName, 'IsInvalid'));
14
25
  };
15
- var validateInclusion = function validateInclusion(fieldValue, fieldName, includedIn) {
26
+ var validateNumericality = function validateNumericality(fieldValue, fieldName, numericality) {
27
+ if (!numericality) return fieldValue;
28
+ var numericValue = Number(fieldValue);
29
+ if (Number.isNaN(numericValue) || !Number.isFinite(numericValue)) {
30
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
31
+ }
32
+ if (numericality === true) return numericValue;
33
+ if (numericality.onlyInteger && !Number.isInteger(numericValue)) {
34
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
35
+ }
36
+ if (numericality.greaterThan !== undefined && numericValue <= numericality.greaterThan) {
37
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
38
+ }
39
+ if (numericality.greaterThanOrEqualTo !== undefined && numericValue < numericality.greaterThanOrEqualTo) {
40
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
41
+ }
42
+ if (numericality.lessThan !== undefined && numericValue >= numericality.lessThan) {
43
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
44
+ }
45
+ if (numericality.lessThanOrEqualTo !== undefined && numericValue > numericality.lessThanOrEqualTo) {
46
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
47
+ }
48
+ return numericValue;
49
+ };
50
+ var validateInclusion = function validateInclusion(fieldValue, fieldName, includedIn, pattern, numericality) {
16
51
  if (fieldName.endsWith('[]')) {
17
52
  // if the array has only 1 element, fieldValue is a string, not an array
18
53
  var arrayValue = fieldValue.constructor === Array ? fieldValue : [fieldValue];
19
54
  if (!arrayValue.every(function (value) {
20
55
  return includedIn === null || includedIn === void 0 ? void 0 : includedIn.includes(value);
21
56
  })) {
22
- throw new Error("".concat(fieldName, "IsInvalid"));
57
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
58
+ }
59
+ arrayValue.forEach(function (value) {
60
+ return validatePattern(value, fieldName, pattern);
61
+ });
62
+ if (numericality) {
63
+ return arrayValue.map(function (value) {
64
+ return validateNumericality(value, fieldName, numericality);
65
+ });
23
66
  }
24
67
  return arrayValue;
25
68
  } else {
26
69
  if (includedIn && !includedIn.includes(fieldValue)) {
27
- throw new Error("".concat(fieldName, "IsInvalid"));
70
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
28
71
  }
29
- return fieldValue;
72
+ validatePattern(fieldValue, fieldName, pattern);
73
+ return validateNumericality(fieldValue, fieldName, numericality);
30
74
  }
31
75
  };
32
76
  export var validField = function validField(req, fieldName, options) {
@@ -38,12 +82,14 @@ export var validField = function validField(req, fieldName, options) {
38
82
  return undefined;
39
83
  }
40
84
  validateLength(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.minLength, options === null || options === void 0 ? void 0 : options.maxLength);
41
- return validateInclusion(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.includedIn);
85
+ return validateInclusion(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.includedIn, options === null || options === void 0 ? void 0 : options.match, options === null || options === void 0 ? void 0 : options.numericality);
42
86
  };
43
87
  export var validEmail = function validEmail(req) {
44
88
  var _req$body2;
89
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
45
90
  var email = req.query.email || ((_req$body2 = req.body) === null || _req$body2 === void 0 ? void 0 : _req$body2.email);
46
91
  if (!email) {
92
+ if (options.optional) return undefined;
47
93
  throw new Error('emailRequired');
48
94
  }
49
95
  if (!emailIsValid(email)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "light-paradate",
3
- "version": "1.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "Lightweight request params validator",
5
5
  "author": "Tamas Kamaras",
6
6
  "repository": {
@@ -9,11 +9,14 @@
9
9
  },
10
10
  "main": "dist/cjs/index.js",
11
11
  "module": "dist/esm/index.js",
12
+ "types": "dist/cjs/index.d.ts",
12
13
  "type": "module",
13
14
  "exports": {
14
15
  ".": {
16
+ "types": "./dist/cjs/index.d.ts",
15
17
  "require": "./dist/cjs/index.js",
16
- "import": "./dist/esm/index.js"
18
+ "import": "./dist/esm/index.js",
19
+ "default": "./dist/esm/index.js"
17
20
  }
18
21
  },
19
22
  "files": [