light-paradate 2.1.2 → 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
 
@@ -1,7 +1,8 @@
1
1
  import type { ParsedQs } from 'qs';
2
2
  import type { ParamsDictionary } from 'express-serve-static-core';
3
3
  interface OptionsType {
4
- includedIn?: string[];
4
+ allowNull?: boolean;
5
+ includedIn?: string[] | number[];
5
6
  match?: RegExp;
6
7
  minLength?: number;
7
8
  maxLength?: number;
@@ -21,8 +22,13 @@ interface FieldValuesType {
21
22
  }
22
23
  type ReqOrFieldType = ParamsDictionary | ParsedQs | FieldValuesType;
23
24
  type ValidFieldReturnType = string | string[] | number | number[] | undefined;
24
- type ValidFieldType = (reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType) => ValidFieldReturnType;
25
- export declare const validField: ValidFieldType;
26
- type ValidEmailFunctionType = (reqOrFieldValues: ReqOrFieldType, options?: Pick<OptionsType, 'optional'>) => string | undefined;
27
- export declare const validEmail: ValidEmailFunctionType;
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;
28
34
  export {};
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validEmail = exports.validField = void 0;
3
+ exports.validField = validField;
4
+ exports.validEmail = validEmail;
4
5
  const email_validator_1 = require("email-validator");
5
6
  const formatFieldNameForError = (fieldName) => {
6
7
  const hasArraySuffix = fieldName.endsWith('[]');
@@ -58,10 +59,10 @@ const validateNumericality = (fieldValue, fieldName, numericality) => {
58
59
  return numericValue;
59
60
  };
60
61
  const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
62
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
61
63
  if (fieldName.endsWith('[]')) {
62
- // if the array has only 1 element, fieldValue is a string, not an array
63
- const arrayValue = (fieldValue.constructor === Array ? fieldValue : [fieldValue]);
64
- if (!arrayValue.every(value => includedIn?.includes(value))) {
64
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
65
+ if (!arrayValue.every(isIncluded)) {
65
66
  throw new Error(fieldError(fieldName, 'IsInvalid'));
66
67
  }
67
68
  arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
@@ -71,34 +72,43 @@ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numerical
71
72
  return arrayValue;
72
73
  }
73
74
  else {
74
- if (includedIn && !includedIn.includes(fieldValue)) {
75
+ if (includedIn && !isIncluded(fieldValue)) {
75
76
  throw new Error(fieldError(fieldName, 'IsInvalid'));
76
77
  }
77
78
  validatePattern(fieldValue, fieldName, pattern);
78
79
  return validateNumericality(fieldValue, fieldName, numericality);
79
80
  }
80
81
  };
81
- const fieldValueFrom = (reqOrFieldValues, fieldName) => {
82
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
83
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
82
84
  if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
83
- const req = reqOrFieldValues;
84
- return req.params?.[fieldName] || req.query?.[fieldName] || req.body?.[fieldName];
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;
85
91
  }
86
- return reqOrFieldValues[fieldName];
92
+ const value = reqOrFieldValues[fieldName];
93
+ return isPresent(value) ? value : undefined;
87
94
  };
88
- const validField = (reqOrFieldValues, fieldName, options) => {
95
+ function validField(reqOrFieldValues, fieldName, options) {
89
96
  if (!options)
90
97
  throw new Error('optionsRequired');
91
- const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName);
92
- if (!fieldValue) {
98
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
99
+ if (fieldValue === null)
100
+ return null;
101
+ if (fieldValue === undefined) {
93
102
  validateRequired(options, fieldName);
94
103
  return undefined;
95
104
  }
96
105
  validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
97
106
  return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
98
- };
99
- exports.validField = validField;
100
- const validEmail = (reqOrFieldValues, options = {}) => {
101
- const email = fieldValueFrom(reqOrFieldValues, 'email');
107
+ }
108
+ function validEmail(reqOrFieldValues, options = {}) {
109
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
110
+ if (email === null)
111
+ return null;
102
112
  if (!email) {
103
113
  if (options.optional)
104
114
  return undefined;
@@ -108,5 +118,4 @@ const validEmail = (reqOrFieldValues, options = {}) => {
108
118
  throw new Error('emailInvalid');
109
119
  }
110
120
  return email;
111
- };
112
- exports.validEmail = validEmail;
121
+ }
package/dist/esm/index.js CHANGED
@@ -55,10 +55,10 @@ const validateNumericality = (fieldValue, fieldName, numericality) => {
55
55
  return numericValue;
56
56
  };
57
57
  const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
58
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
58
59
  if (fieldName.endsWith('[]')) {
59
- // if the array has only 1 element, fieldValue is a string, not an array
60
- const arrayValue = (fieldValue.constructor === Array ? fieldValue : [fieldValue]);
61
- if (!arrayValue.every(value => includedIn?.includes(value))) {
60
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
61
+ if (!arrayValue.every(isIncluded)) {
62
62
  throw new Error(fieldError(fieldName, 'IsInvalid'));
63
63
  }
64
64
  arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
@@ -68,33 +68,43 @@ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numerical
68
68
  return arrayValue;
69
69
  }
70
70
  else {
71
- if (includedIn && !includedIn.includes(fieldValue)) {
71
+ if (includedIn && !isIncluded(fieldValue)) {
72
72
  throw new Error(fieldError(fieldName, 'IsInvalid'));
73
73
  }
74
74
  validatePattern(fieldValue, fieldName, pattern);
75
75
  return validateNumericality(fieldValue, fieldName, numericality);
76
76
  }
77
77
  };
78
- const fieldValueFrom = (reqOrFieldValues, fieldName) => {
78
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
79
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
79
80
  if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
80
- const req = reqOrFieldValues;
81
- return req.params?.[fieldName] || req.query?.[fieldName] || req.body?.[fieldName];
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;
82
87
  }
83
- return reqOrFieldValues[fieldName];
88
+ const value = reqOrFieldValues[fieldName];
89
+ return isPresent(value) ? value : undefined;
84
90
  };
85
- export const validField = (reqOrFieldValues, fieldName, options) => {
91
+ export function validField(reqOrFieldValues, fieldName, options) {
86
92
  if (!options)
87
93
  throw new Error('optionsRequired');
88
- const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName);
89
- if (!fieldValue) {
94
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
95
+ if (fieldValue === null)
96
+ return null;
97
+ if (fieldValue === undefined) {
90
98
  validateRequired(options, fieldName);
91
99
  return undefined;
92
100
  }
93
101
  validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
94
102
  return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
95
- };
96
- export const validEmail = (reqOrFieldValues, options = {}) => {
97
- const email = fieldValueFrom(reqOrFieldValues, 'email');
103
+ }
104
+ export function validEmail(reqOrFieldValues, options = {}) {
105
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
106
+ if (email === null)
107
+ return null;
98
108
  if (!email) {
99
109
  if (options.optional)
100
110
  return undefined;
@@ -104,4 +114,4 @@ export const validEmail = (reqOrFieldValues, options = {}) => {
104
114
  throw new Error('emailInvalid');
105
115
  }
106
116
  return email;
107
- };
117
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { ParsedQs } from 'qs';
2
2
  import type { ParamsDictionary } from 'express-serve-static-core';
3
3
  interface OptionsType {
4
- includedIn?: string[];
4
+ allowNull?: boolean;
5
+ includedIn?: string[] | number[];
5
6
  match?: RegExp;
6
7
  minLength?: number;
7
8
  maxLength?: number;
@@ -21,8 +22,13 @@ interface FieldValuesType {
21
22
  }
22
23
  type ReqOrFieldType = ParamsDictionary | ParsedQs | FieldValuesType;
23
24
  type ValidFieldReturnType = string | string[] | number | number[] | undefined;
24
- type ValidFieldType = (reqOrFieldValues: ReqOrFieldType, fieldName: string, options: OptionsType) => ValidFieldReturnType;
25
- export declare const validField: ValidFieldType;
26
- type ValidEmailFunctionType = (reqOrFieldValues: ReqOrFieldType, options?: Pick<OptionsType, 'optional'>) => string | undefined;
27
- export declare const validEmail: ValidEmailFunctionType;
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;
28
34
  export {};
package/dist/index.js CHANGED
@@ -55,10 +55,10 @@ const validateNumericality = (fieldValue, fieldName, numericality) => {
55
55
  return numericValue;
56
56
  };
57
57
  const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numericality) => {
58
+ const isIncluded = (value) => includedIn?.some(allowed => allowed === value || (typeof allowed === 'number' && String(allowed) === value)) ?? false;
58
59
  if (fieldName.endsWith('[]')) {
59
- // if the array has only 1 element, fieldValue is a string, not an array
60
- const arrayValue = (fieldValue.constructor === Array ? fieldValue : [fieldValue]);
61
- if (!arrayValue.every(value => includedIn?.includes(value))) {
60
+ const arrayValue = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
61
+ if (!arrayValue.every(isIncluded)) {
62
62
  throw new Error(fieldError(fieldName, 'IsInvalid'));
63
63
  }
64
64
  arrayValue.forEach(value => validatePattern(value, fieldName, pattern));
@@ -68,33 +68,43 @@ const validateInclusion = (fieldValue, fieldName, includedIn, pattern, numerical
68
68
  return arrayValue;
69
69
  }
70
70
  else {
71
- if (includedIn && !includedIn.includes(fieldValue)) {
71
+ if (includedIn && !isIncluded(fieldValue)) {
72
72
  throw new Error(fieldError(fieldName, 'IsInvalid'));
73
73
  }
74
74
  validatePattern(fieldValue, fieldName, pattern);
75
75
  return validateNumericality(fieldValue, fieldName, numericality);
76
76
  }
77
77
  };
78
- const fieldValueFrom = (reqOrFieldValues, fieldName) => {
78
+ const fieldValueFrom = (reqOrFieldValues, fieldName, allowNull = false) => {
79
+ const isPresent = (value) => Boolean(value) || value === 0 || (allowNull && value === null);
79
80
  if ('query' in reqOrFieldValues || 'body' in reqOrFieldValues || 'params' in reqOrFieldValues) {
80
- const req = reqOrFieldValues;
81
- return req.params?.[fieldName] || req.query?.[fieldName] || req.body?.[fieldName];
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;
82
87
  }
83
- return reqOrFieldValues[fieldName];
88
+ const value = reqOrFieldValues[fieldName];
89
+ return isPresent(value) ? value : undefined;
84
90
  };
85
- export const validField = (reqOrFieldValues, fieldName, options) => {
91
+ export function validField(reqOrFieldValues, fieldName, options) {
86
92
  if (!options)
87
93
  throw new Error('optionsRequired');
88
- const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName);
89
- if (!fieldValue) {
94
+ const fieldValue = fieldValueFrom(reqOrFieldValues, fieldName, options.allowNull);
95
+ if (fieldValue === null)
96
+ return null;
97
+ if (fieldValue === undefined) {
90
98
  validateRequired(options, fieldName);
91
99
  return undefined;
92
100
  }
93
101
  validateLength(fieldValue, fieldName, options?.minLength, options?.maxLength);
94
102
  return validateInclusion(fieldValue, fieldName, options?.includedIn, options?.match, options?.numericality);
95
- };
96
- export const validEmail = (reqOrFieldValues, options = {}) => {
97
- const email = fieldValueFrom(reqOrFieldValues, 'email');
103
+ }
104
+ export function validEmail(reqOrFieldValues, options = {}) {
105
+ const email = fieldValueFrom(reqOrFieldValues, 'email', options.allowNull);
106
+ if (email === null)
107
+ return null;
98
108
  if (!email) {
99
109
  if (options.optional)
100
110
  return undefined;
@@ -104,4 +114,4 @@ export const validEmail = (reqOrFieldValues, options = {}) => {
104
114
  throw new Error('emailInvalid');
105
115
  }
106
116
  return email;
107
- };
117
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "light-paradate",
3
- "version": "2.1.2",
3
+ "version": "2.2.0",
4
4
  "description": "Lightweight request params validator",
5
5
  "author": "Tamas Kamaras",
6
6
  "repository": {
@@ -29,8 +29,9 @@
29
29
  "build:cjs": "tsc --project tsconfig.json --module commonjs --outDir dist/cjs --declarationDir dist/cjs --emitDeclarationOnly false",
30
30
  "build:esm": "tsc --project tsconfig.json --module esnext --outDir dist/esm --declaration false --emitDeclarationOnly false",
31
31
  "build": "npm run type-check && npm run build:cjs && npm run build:esm",
32
- "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js",
33
- "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"
34
35
  },
35
36
  "keywords": [
36
37
  "node",