light-paradate 2.1.1 → 2.2.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
@@ -35,6 +35,20 @@ yarn add light-paradate
35
35
  ```
36
36
 
37
37
  ## Usage
38
+
39
+ ### Omitted fields and explicit `null`
40
+
41
+ Both validators treat `null` as missing by default. `optional: true` lets a missing field return `undefined`. `allowNull: true` returns an explicit `null` before running any format or length checks.
42
+
43
+ | Options passed to `validEmail(req.body, options)` | Empty body `{}` | Body with `{ email: null }` |
44
+ | --- | --- | --- |
45
+ | `{}` | Throws `emailRequired` | Throws `emailRequired` |
46
+ | `{ optional: true }` | `undefined` | `undefined` |
47
+ | `{ allowNull: true }` | Throws `emailRequired` | `null` |
48
+ | `{ optional: true, allowNull: true }` | `undefined` | `null` |
49
+
50
+ `validField` allows omission by default, including when you supply a `match` pattern. With `match` and `allowNull: true`, an update handler can use `undefined` to keep the current image URL, `null` to clear it, and a matching string to replace it. If `required: true` or a positive `minLength` makes the field mandatory, add `optional: true` to allow omission.
51
+
38
52
  ### validField
39
53
 
40
54
  `validField(reqOrFieldValues, fieldName, options)`
@@ -48,7 +62,9 @@ const parentId = validField(req.params, 'parent_id', { numericality: { onlyInteg
48
62
  const id = validField(req, 'id', { match: /^[1-9]\d*$/ });
49
63
  const orderBy = validField(req.query, 'orderBy', { includedIn: ['name', 'email', 'status'] });
50
64
  const statuses = validField(req.query, 'statuses[]', { includedIn: ['invited', 'active'] });
65
+ const priority = validField(req.query, 'priority', { includedIn: [0, 1, 2], numericality: true });
51
66
  const firstName = validField(req.body, 'firstName', { minLength: 5 });
67
+ const imageUrl = validField(req.body, 'image_url', { allowNull: true, match: /^https?:\/\/.+$/ });
52
68
  ```
53
69
 
54
70
  #### Parameters
@@ -57,15 +73,17 @@ const firstName = validField(req.body, 'firstName', { minLength: 5 });
57
73
  - `options`: An optional object containing validation requirements.
58
74
  Possible values for the `options` argument include:
59
75
  - `optional`: boolean - Allows the field to be omitted even when other validators such as `minLength` are configured.
76
+ - `allowNull` (boolean) accepts an explicit `null`, including for a required field.
60
77
  - `required`: boolean - Indicates whether the field must have a non-empty value.
61
78
  - `minLength`: number - Specifies the minimum length the field value should have.
62
79
  - `maxLength`: number - Specifies the maximum length the field value can have.
63
80
  - `match`: RegExp - Validates the field value against a regular expression.
64
81
  - `numericality`: boolean | object - Converts the field to a number and validates numeric constraints. Supported object keys: `onlyInteger`, `greaterThan`, `greaterThanOrEqualTo`, `lessThan`, `lessThanOrEqualTo`.
65
- - `includedIn`: string[] - An array of valid strings that the field value must match to pass validation.
82
+ - `includedIn` (`string[] | number[]`) checks each field value against the allowed values. String lists match strings exactly. A numeric list such as `[1, 2]` also accepts the strings `'1'` and `'2'`. Use `numericality: true` to return those strings as numbers.
66
83
 
67
84
  #### Return Value
68
85
  - If valid, returns the string, number, string array, or number array (in case of fields that use `[]` notation).
86
+ - Returns `null` when `allowNull: true` is set and the field is explicitly `null`.
69
87
  - Returns `undefined` if the field is not required and not present, or if `optional: true` is set and the field is omitted.
70
88
  - Throws an error if validation fails.
71
89
 
@@ -87,15 +105,17 @@ Extracts and validates the "email" field from `req.query` or `req.body`, ensurin
87
105
  example:
88
106
  ```js
89
107
  const email = validEmail(req);
90
- const alternateEmail = validEmail(req, { optional: true });
108
+ const alternateEmail = validEmail(req, { optional: true, allowNull: true });
91
109
  ```
92
110
  #### Parameters
93
111
  - `req`: A request-like object with query and body.
94
112
  - `options`: Optional configuration.
95
113
  - `optional`: boolean - Allows `email` to be omitted. If present, it is still validated.
114
+ - `allowNull` (boolean) accepts an explicit `null`. Omission still requires `optional: true`.
96
115
 
97
116
  #### Return Value
98
117
  - Returns a valid email string if validation passes.
118
+ - Returns `null` if `allowNull: true` is set and the email is explicitly `null`.
99
119
  - Returns `undefined` if `optional: true` is set and the email is missing.
100
120
  - Throws an error if the email is invalid, or if it is missing without `optional: true`.
101
121
 
@@ -0,0 +1,34 @@
1
+ import type { ParsedQs } from 'qs';
2
+ import type { ParamsDictionary } from 'express-serve-static-core';
3
+ interface OptionsType {
4
+ allowNull?: boolean;
5
+ includedIn?: string[] | number[];
6
+ match?: RegExp;
7
+ minLength?: number;
8
+ maxLength?: number;
9
+ numericality?: boolean | NumericalityOptionsType;
10
+ optional?: boolean;
11
+ required?: boolean;
12
+ }
13
+ interface NumericalityOptionsType {
14
+ onlyInteger?: boolean;
15
+ greaterThan?: number;
16
+ greaterThanOrEqualTo?: number;
17
+ lessThan?: number;
18
+ lessThanOrEqualTo?: number;
19
+ }
20
+ interface FieldValuesType {
21
+ [key: string]: any;
22
+ }
23
+ type ReqOrFieldType = ParamsDictionary | ParsedQs | FieldValuesType;
24
+ type ValidFieldReturnType = string | string[] | number | number[] | undefined;
25
+ export declare function validField(reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType & {
26
+ allowNull?: false;
27
+ }): ValidFieldReturnType;
28
+ export declare function validField(reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType): ValidFieldReturnType | null;
29
+ type ValidEmailOptions = Pick<OptionsType, 'optional' | 'allowNull'>;
30
+ export declare function validEmail(reqOrFieldValues: ReqOrFieldType, options?: ValidEmailOptions & {
31
+ allowNull?: false;
32
+ }): string | undefined;
33
+ export declare function validEmail(reqOrFieldValues: ReqOrFieldType, options?: ValidEmailOptions): string | null | undefined;
34
+ export {};
package/dist/cjs/index.js CHANGED
@@ -1,111 +1,121 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.validField = exports.validEmail = void 0;
7
- var _emailValidator = require("email-validator");
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;
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validField = validField;
4
+ exports.validEmail = validEmail;
5
+ const email_validator_1 = require("email-validator");
6
+ const formatFieldNameForError = (fieldName) => {
7
+ const hasArraySuffix = fieldName.endsWith('[]');
8
+ const normalizedFieldName = hasArraySuffix ? fieldName.slice(0, -2) : fieldName;
9
+ const camelizedFieldName = normalizedFieldName.replace(/[_-]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
10
+ return hasArraySuffix ? `${camelizedFieldName}[]` : camelizedFieldName;
15
11
  };
16
- var fieldError = function fieldError(fieldName, errorSuffix) {
17
- return "".concat(formatFieldNameForError(fieldName)).concat(errorSuffix);
12
+ const fieldError = (fieldName, errorSuffix) => {
13
+ return `${formatFieldNameForError(fieldName)}${errorSuffix}`;
18
14
  };
19
- var validateRequired = function validateRequired(options, fieldName) {
20
- if (options.optional) return;
21
- if (options.required || options.minLength) throw new Error(fieldError(fieldName, 'Required'));
15
+ const validateRequired = (options, fieldName) => {
16
+ if (options.optional)
17
+ return;
18
+ if (options.required || options.minLength)
19
+ throw new Error(fieldError(fieldName, 'Required'));
22
20
  };
23
- var validateLength = function validateLength(fieldValue, fieldName, minLength, maxLength) {
24
- if (!minLength && !maxLength) return;
25
- if (minLength && fieldValue.length < minLength) throw new Error(fieldError(fieldName, 'TooShort'));
26
- if (maxLength && fieldValue.length > maxLength) throw new Error(fieldError(fieldName, 'TooLong'));
21
+ const validateLength = (fieldValue, fieldName, minLength, maxLength) => {
22
+ if (!minLength && !maxLength)
23
+ return;
24
+ if (minLength && fieldValue.length < minLength)
25
+ throw new Error(fieldError(fieldName, 'TooShort'));
26
+ if (maxLength && fieldValue.length > maxLength)
27
+ throw new Error(fieldError(fieldName, 'TooLong'));
27
28
  };
28
- var validatePattern = function validatePattern(fieldValue, fieldName, pattern) {
29
- if (!pattern) return;
30
- if (!pattern.test(fieldValue)) throw new Error(fieldError(fieldName, 'IsInvalid'));
29
+ const validatePattern = (fieldValue, fieldName, pattern) => {
30
+ if (!pattern)
31
+ return;
32
+ if (!pattern.test(fieldValue))
33
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
31
34
  };
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) {
57
- if (fieldName.endsWith('[]')) {
58
- // if the array has only 1 element, fieldValue is a string, not an array
59
- var arrayValue = fieldValue.constructor === Array ? fieldValue : [fieldValue];
60
- if (!arrayValue.every(function (value) {
61
- return includedIn === null || includedIn === void 0 ? void 0 : includedIn.includes(value);
62
- })) {
63
- throw new Error(fieldError(fieldName, 'IsInvalid'));
35
+ const validateNumericality = (fieldValue, fieldName, numericality) => {
36
+ if (!numericality)
37
+ return fieldValue;
38
+ const numericValue = Number(fieldValue);
39
+ if (Number.isNaN(numericValue) || !Number.isFinite(numericValue)) {
40
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
41
+ }
42
+ if (numericality === true)
43
+ return numericValue;
44
+ if (numericality.onlyInteger && !Number.isInteger(numericValue)) {
45
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
46
+ }
47
+ if (numericality.greaterThan !== undefined && numericValue <= numericality.greaterThan) {
48
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
64
49
  }
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
- });
50
+ if (numericality.greaterThanOrEqualTo !== undefined && numericValue < numericality.greaterThanOrEqualTo) {
51
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
72
52
  }
73
- return arrayValue;
74
- } else {
75
- if (includedIn && !includedIn.includes(fieldValue)) {
76
- throw new Error(fieldError(fieldName, 'IsInvalid'));
53
+ if (numericality.lessThan !== undefined && numericValue >= numericality.lessThan) {
54
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
77
55
  }
78
- validatePattern(fieldValue, fieldName, pattern);
79
- return validateNumericality(fieldValue, fieldName, numericality);
80
- }
56
+ if (numericality.lessThanOrEqualTo !== undefined && numericValue > numericality.lessThanOrEqualTo) {
57
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
58
+ }
59
+ return numericValue;
81
60
  };
82
- var fieldValueFrom = function fieldValueFrom(reqOrFieldValues, fieldName) {
83
- if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
84
- var _req$params, _req$query, _req$body;
85
- var req = reqOrFieldValues;
86
- return ((_req$params = req.params) === null || _req$params === void 0 ? void 0 : _req$params[fieldName]) || ((_req$query = req.query) === null || _req$query === void 0 ? void 0 : _req$query[fieldName]) || ((_req$body = req.body) === null || _req$body === void 0 ? void 0 : _req$body[fieldName]);
87
- }
88
- return reqOrFieldValues[fieldName];
61
+ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
62
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
63
+ if (fieldName.endsWith('[]')) {
64
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
65
+ if (!arrayValue.every(isIncluded)) {
66
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
67
+ }
68
+ arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
69
+ if (numericality) {
70
+ return arrayValue.map(value => validateNumericality(value, fieldName, numericality));
71
+ }
72
+ return arrayValue;
73
+ }
74
+ else {
75
+ if (includedIn && !isIncluded(fieldValue)) {
76
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
77
+ }
78
+ validatePattern(fieldValue, fieldName, pattern);
79
+ return validateNumericality(fieldValue, fieldName, numericality);
80
+ }
89
81
  };
90
- var validField = exports.validField = function validField(reqOrFieldValues, fieldName, options) {
91
- if (!options) throw new Error('optionsRequired');
92
- var fieldValue = fieldValueFrom(reqOrFieldValues, fieldName);
93
- if (!fieldValue) {
94
- validateRequired(options, fieldName);
95
- return undefined;
96
- }
97
- validateLength(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.minLength, options === null || options === void 0 ? void 0 : options.maxLength);
98
- 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);
82
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
83
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
84
+ if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
85
+ for (const source of ['params', 'query', 'body']) {
86
+ const value = reqOrFieldValues[source]?.[fieldName];
87
+ if (isPresent(value))
88
+ return value;
89
+ }
90
+ return undefined;
91
+ }
92
+ const value = reqOrFieldValues[fieldName];
93
+ return isPresent(value) ? value : undefined;
99
94
  };
100
- var validEmail = exports.validEmail = function validEmail(reqOrFieldValues) {
101
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
102
- var email = fieldValueFrom(reqOrFieldValues, 'email');
103
- if (!email) {
104
- if (options.optional) return undefined;
105
- throw new Error('emailRequired');
106
- }
107
- if (!(0, _emailValidator.validate)(email)) {
108
- throw new Error('emailInvalid');
109
- }
110
- return email;
111
- };
95
+ function validField(reqOrFieldValues, fieldName, options) {
96
+ if (!options)
97
+ throw new Error('optionsRequired');
98
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
99
+ if (fieldValue === null)
100
+ return null;
101
+ if (fieldValue === undefined) {
102
+ validateRequired(options, fieldName);
103
+ return undefined;
104
+ }
105
+ validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
106
+ return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
107
+ }
108
+ function validEmail(reqOrFieldValues, options = {}) {
109
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
110
+ if (email === null)
111
+ return null;
112
+ if (!email) {
113
+ if (options.optional)
114
+ return undefined;
115
+ throw new Error('emailRequired');
116
+ }
117
+ if (!(0, email_validator_1.validate)(email)) {
118
+ throw new Error('emailInvalid');
119
+ }
120
+ return email;
121
+ }
package/dist/esm/index.js CHANGED
@@ -1,105 +1,117 @@
1
1
  import { validate as emailIsValid } from 'email-validator';
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;
2
+ const formatFieldNameForError = (fieldName) => {
3
+ const hasArraySuffix = fieldName.endsWith('[]');
4
+ const normalizedFieldName = hasArraySuffix ? fieldName.slice(0, -2) : fieldName;
5
+ const camelizedFieldName = normalizedFieldName.replace(/[_-]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
6
+ return hasArraySuffix ? `${camelizedFieldName}[]` : camelizedFieldName;
9
7
  };
10
- var fieldError = function fieldError(fieldName, errorSuffix) {
11
- return "".concat(formatFieldNameForError(fieldName)).concat(errorSuffix);
8
+ const fieldError = (fieldName, errorSuffix) => {
9
+ return `${formatFieldNameForError(fieldName)}${errorSuffix}`;
12
10
  };
13
- var validateRequired = function validateRequired(options, fieldName) {
14
- if (options.optional) return;
15
- if (options.required || options.minLength) throw new Error(fieldError(fieldName, 'Required'));
11
+ const validateRequired = (options, fieldName) => {
12
+ if (options.optional)
13
+ return;
14
+ if (options.required || options.minLength)
15
+ throw new Error(fieldError(fieldName, 'Required'));
16
16
  };
17
- var validateLength = function validateLength(fieldValue, fieldName, minLength, maxLength) {
18
- if (!minLength && !maxLength) return;
19
- if (minLength && fieldValue.length < minLength) throw new Error(fieldError(fieldName, 'TooShort'));
20
- if (maxLength && fieldValue.length > maxLength) throw new Error(fieldError(fieldName, 'TooLong'));
17
+ const validateLength = (fieldValue, fieldName, minLength, maxLength) => {
18
+ if (!minLength && !maxLength)
19
+ return;
20
+ if (minLength && fieldValue.length < minLength)
21
+ throw new Error(fieldError(fieldName, 'TooShort'));
22
+ if (maxLength && fieldValue.length > maxLength)
23
+ throw new Error(fieldError(fieldName, 'TooLong'));
21
24
  };
22
- var validatePattern = function validatePattern(fieldValue, fieldName, pattern) {
23
- if (!pattern) return;
24
- if (!pattern.test(fieldValue)) throw new Error(fieldError(fieldName, 'IsInvalid'));
25
+ const validatePattern = (fieldValue, fieldName, pattern) => {
26
+ if (!pattern)
27
+ return;
28
+ if (!pattern.test(fieldValue))
29
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
25
30
  };
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) {
51
- if (fieldName.endsWith('[]')) {
52
- // if the array has only 1 element, fieldValue is a string, not an array
53
- var arrayValue = fieldValue.constructor === Array ? fieldValue : [fieldValue];
54
- if (!arrayValue.every(function (value) {
55
- return includedIn === null || includedIn === void 0 ? void 0 : includedIn.includes(value);
56
- })) {
57
- throw new Error(fieldError(fieldName, 'IsInvalid'));
31
+ const validateNumericality = (fieldValue, fieldName, numericality) => {
32
+ if (!numericality)
33
+ return fieldValue;
34
+ const numericValue = Number(fieldValue);
35
+ if (Number.isNaN(numericValue) || !Number.isFinite(numericValue)) {
36
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
37
+ }
38
+ if (numericality === true)
39
+ return numericValue;
40
+ if (numericality.onlyInteger && !Number.isInteger(numericValue)) {
41
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
42
+ }
43
+ if (numericality.greaterThan !== undefined && numericValue <= numericality.greaterThan) {
44
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
58
45
  }
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
- });
46
+ if (numericality.greaterThanOrEqualTo !== undefined && numericValue < numericality.greaterThanOrEqualTo) {
47
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
66
48
  }
67
- return arrayValue;
68
- } else {
69
- if (includedIn && !includedIn.includes(fieldValue)) {
70
- throw new Error(fieldError(fieldName, 'IsInvalid'));
49
+ if (numericality.lessThan !== undefined && numericValue >= numericality.lessThan) {
50
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
71
51
  }
72
- validatePattern(fieldValue, fieldName, pattern);
73
- return validateNumericality(fieldValue, fieldName, numericality);
74
- }
52
+ if (numericality.lessThanOrEqualTo !== undefined && numericValue > numericality.lessThanOrEqualTo) {
53
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
54
+ }
55
+ return numericValue;
75
56
  };
76
- var fieldValueFrom = function fieldValueFrom(reqOrFieldValues, fieldName) {
77
- if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
78
- var _req$params, _req$query, _req$body;
79
- var req = reqOrFieldValues;
80
- return ((_req$params = req.params) === null || _req$params === void 0 ? void 0 : _req$params[fieldName]) || ((_req$query = req.query) === null || _req$query === void 0 ? void 0 : _req$query[fieldName]) || ((_req$body = req.body) === null || _req$body === void 0 ? void 0 : _req$body[fieldName]);
81
- }
82
- return reqOrFieldValues[fieldName];
57
+ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
58
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
59
+ if (fieldName.endsWith('[]')) {
60
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
61
+ if (!arrayValue.every(isIncluded)) {
62
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
63
+ }
64
+ arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
65
+ if (numericality) {
66
+ return arrayValue.map(value => validateNumericality(value, fieldName, numericality));
67
+ }
68
+ return arrayValue;
69
+ }
70
+ else {
71
+ if (includedIn && !isIncluded(fieldValue)) {
72
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
73
+ }
74
+ validatePattern(fieldValue, fieldName, pattern);
75
+ return validateNumericality(fieldValue, fieldName, numericality);
76
+ }
83
77
  };
84
- export var validField = function validField(reqOrFieldValues, fieldName, options) {
85
- if (!options) throw new Error('optionsRequired');
86
- var fieldValue = fieldValueFrom(reqOrFieldValues, fieldName);
87
- if (!fieldValue) {
88
- validateRequired(options, fieldName);
89
- return undefined;
90
- }
91
- validateLength(fieldValue, fieldName, options === null || options === void 0 ? void 0 : options.minLength, options === null || options === void 0 ? void 0 : options.maxLength);
92
- 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);
78
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
79
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
80
+ if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
81
+ for (const source of ['params', 'query', 'body']) {
82
+ const value = reqOrFieldValues[source]?.[fieldName];
83
+ if (isPresent(value))
84
+ return value;
85
+ }
86
+ return undefined;
87
+ }
88
+ const value = reqOrFieldValues[fieldName];
89
+ return isPresent(value) ? value : undefined;
93
90
  };
94
- export var validEmail = function validEmail(reqOrFieldValues) {
95
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
96
- var email = fieldValueFrom(reqOrFieldValues, 'email');
97
- if (!email) {
98
- if (options.optional) return undefined;
99
- throw new Error('emailRequired');
100
- }
101
- if (!emailIsValid(email)) {
102
- throw new Error('emailInvalid');
103
- }
104
- return email;
105
- };
91
+ export function validField(reqOrFieldValues, fieldName, options) {
92
+ if (!options)
93
+ throw new Error('optionsRequired');
94
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
95
+ if (fieldValue === null)
96
+ return null;
97
+ if (fieldValue === undefined) {
98
+ validateRequired(options, fieldName);
99
+ return undefined;
100
+ }
101
+ validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
102
+ return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
103
+ }
104
+ export function validEmail(reqOrFieldValues, options = {}) {
105
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
106
+ if (email === null)
107
+ return null;
108
+ if (!email) {
109
+ if (options.optional)
110
+ return undefined;
111
+ throw new Error('emailRequired');
112
+ }
113
+ if (!emailIsValid(email)) {
114
+ throw new Error('emailInvalid');
115
+ }
116
+ return email;
117
+ }
@@ -0,0 +1,34 @@
1
+ import type { ParsedQs } from 'qs';
2
+ import type { ParamsDictionary } from 'express-serve-static-core';
3
+ interface OptionsType {
4
+ allowNull?: boolean;
5
+ includedIn?: string[] | number[];
6
+ match?: RegExp;
7
+ minLength?: number;
8
+ maxLength?: number;
9
+ numericality?: boolean | NumericalityOptionsType;
10
+ optional?: boolean;
11
+ required?: boolean;
12
+ }
13
+ interface NumericalityOptionsType {
14
+ onlyInteger?: boolean;
15
+ greaterThan?: number;
16
+ greaterThanOrEqualTo?: number;
17
+ lessThan?: number;
18
+ lessThanOrEqualTo?: number;
19
+ }
20
+ interface FieldValuesType {
21
+ [key: string]: any;
22
+ }
23
+ type ReqOrFieldType = ParamsDictionary | ParsedQs | FieldValuesType;
24
+ type ValidFieldReturnType = string | string[] | number | number[] | undefined;
25
+ export declare function validField(reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType & {
26
+ allowNull?: false;
27
+ }): ValidFieldReturnType;
28
+ export declare function validField(reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType): ValidFieldReturnType | null;
29
+ type ValidEmailOptions = Pick<OptionsType, 'optional' | 'allowNull'>;
30
+ export declare function validEmail(reqOrFieldValues: ReqOrFieldType, options?: ValidEmailOptions & {
31
+ allowNull?: false;
32
+ }): string | undefined;
33
+ export declare function validEmail(reqOrFieldValues: ReqOrFieldType, options?: ValidEmailOptions): string | null | undefined;
34
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,117 @@
1
+ import { validate as emailIsValid } from 'email-validator';
2
+ const formatFieldNameForError = (fieldName) => {
3
+ const hasArraySuffix = fieldName.endsWith('[]');
4
+ const normalizedFieldName = hasArraySuffix ? fieldName.slice(0, -2) : fieldName;
5
+ const camelizedFieldName = normalizedFieldName.replace(/[_-]+([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
6
+ return hasArraySuffix ? `${camelizedFieldName}[]` : camelizedFieldName;
7
+ };
8
+ const fieldError = (fieldName, errorSuffix) => {
9
+ return `${formatFieldNameForError(fieldName)}${errorSuffix}`;
10
+ };
11
+ const validateRequired = (options, fieldName) => {
12
+ if (options.optional)
13
+ return;
14
+ if (options.required || options.minLength)
15
+ throw new Error(fieldError(fieldName, 'Required'));
16
+ };
17
+ const validateLength = (fieldValue, fieldName, minLength, maxLength) => {
18
+ if (!minLength && !maxLength)
19
+ return;
20
+ if (minLength && fieldValue.length < minLength)
21
+ throw new Error(fieldError(fieldName, 'TooShort'));
22
+ if (maxLength && fieldValue.length > maxLength)
23
+ throw new Error(fieldError(fieldName, 'TooLong'));
24
+ };
25
+ const validatePattern = (fieldValue, fieldName, pattern) => {
26
+ if (!pattern)
27
+ return;
28
+ if (!pattern.test(fieldValue))
29
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
30
+ };
31
+ const validateNumericality = (fieldValue, fieldName, numericality) => {
32
+ if (!numericality)
33
+ return fieldValue;
34
+ const numericValue = Number(fieldValue);
35
+ if (Number.isNaN(numericValue) || !Number.isFinite(numericValue)) {
36
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
37
+ }
38
+ if (numericality === true)
39
+ return numericValue;
40
+ if (numericality.onlyInteger && !Number.isInteger(numericValue)) {
41
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
42
+ }
43
+ if (numericality.greaterThan !== undefined && numericValue <= numericality.greaterThan) {
44
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
45
+ }
46
+ if (numericality.greaterThanOrEqualTo !== undefined && numericValue < numericality.greaterThanOrEqualTo) {
47
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
48
+ }
49
+ if (numericality.lessThan !== undefined && numericValue >= numericality.lessThan) {
50
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
51
+ }
52
+ if (numericality.lessThanOrEqualTo !== undefined && numericValue > numericality.lessThanOrEqualTo) {
53
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
54
+ }
55
+ return numericValue;
56
+ };
57
+ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
58
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
59
+ if (fieldName.endsWith('[]')) {
60
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
61
+ if (!arrayValue.every(isIncluded)) {
62
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
63
+ }
64
+ arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
65
+ if (numericality) {
66
+ return arrayValue.map(value => validateNumericality(value, fieldName, numericality));
67
+ }
68
+ return arrayValue;
69
+ }
70
+ else {
71
+ if (includedIn && !isIncluded(fieldValue)) {
72
+ throw new Error(fieldError(fieldName, 'IsInvalid'));
73
+ }
74
+ validatePattern(fieldValue, fieldName, pattern);
75
+ return validateNumericality(fieldValue, fieldName, numericality);
76
+ }
77
+ };
78
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
79
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
80
+ if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
81
+ for (const source of ['params', 'query', 'body']) {
82
+ const value = reqOrFieldValues[source]?.[fieldName];
83
+ if (isPresent(value))
84
+ return value;
85
+ }
86
+ return undefined;
87
+ }
88
+ const value = reqOrFieldValues[fieldName];
89
+ return isPresent(value) ? value : undefined;
90
+ };
91
+ export function validField(reqOrFieldValues, fieldName, options) {
92
+ if (!options)
93
+ throw new Error('optionsRequired');
94
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
95
+ if (fieldValue === null)
96
+ return null;
97
+ if (fieldValue === undefined) {
98
+ validateRequired(options, fieldName);
99
+ return undefined;
100
+ }
101
+ validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
102
+ return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
103
+ }
104
+ export function validEmail(reqOrFieldValues, options = {}) {
105
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
106
+ if (email === null)
107
+ return null;
108
+ if (!email) {
109
+ if (options.optional)
110
+ return undefined;
111
+ throw new Error('emailRequired');
112
+ }
113
+ if (!emailIsValid(email)) {
114
+ throw new Error('emailInvalid');
115
+ }
116
+ return email;
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "light-paradate",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "Lightweight request params validator",
5
5
  "author": "Tamas Kamaras",
6
6
  "repository": {
@@ -20,19 +20,18 @@
20
20
  }
21
21
  },
22
22
  "files": [
23
- "dist/cjs/index.js",
24
- "dist/cjs/index.d.ts",
25
- "dist/esm/index.js",
23
+ "dist",
26
24
  "LICENSE",
27
25
  "README.md"
28
26
  ],
29
27
  "scripts": {
30
28
  "type-check": "tsc",
31
- "build:cjs": "babel src --out-dir dist/cjs --env-name cjs --extensions '.ts'",
32
- "build:esm": "babel src --out-dir dist/esm --env-name esm --extensions '.ts'",
29
+ "build:cjs": "tsc --project tsconfig.json --module commonjs --outDir dist/cjs --declarationDir dist/cjs --emitDeclarationOnly false",
30
+ "build:esm": "tsc --project tsconfig.json --module esnext --outDir dist/esm --declaration false --emitDeclarationOnly false",
33
31
  "build": "npm run type-check && npm run build:cjs && npm run build:esm",
34
- "test": "npm run build && jest --config=tests/jest.config.js",
35
- "lint": "eslint src tests"
32
+ "lint": "eslint src tests",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js"
36
35
  },
37
36
  "keywords": [
38
37
  "node",
@@ -54,17 +53,12 @@
54
53
  "email-validator": "^2.0.4"
55
54
  },
56
55
  "devDependencies": {
57
- "@babel/cli": "^7.26.4",
58
- "@babel/core": "^7.26.0",
59
- "@babel/preset-env": "^7.26.0",
60
- "@babel/preset-typescript": "^7.26.0",
61
- "@eslint/js": "^9.19.0",
56
+ "@eslint/js": "^10.0.1",
62
57
  "@types/express": "^5.0.6",
63
58
  "@typescript-eslint/eslint-plugin": "^8.21.0",
64
59
  "@typescript-eslint/parser": "^8.21.0",
65
- "babel-jest": "^29.7.0",
66
- "eslint": "^9.19.0",
67
- "jest": "^29.7.0",
68
- "typescript": "^5.7.3"
60
+ "eslint": "^10.2.1",
61
+ "jest": "^30.3.0",
62
+ "typescript": "^6.0.3"
69
63
  }
70
64
  }