-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
42 lines (40 loc) · 1.35 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import TValidate from "../TValidate";
import isByteLength from "validator/lib/isByteLength";
/**
* Validates if a string is in the given length range.
*
* @param options.min - Be at least this long.
* @param options.max - Don't be longer than this.
*
* @returns
* A `Guard` that accepts only strings, that is in the given length range.
*
* `guard.name: "string(minLength=<minLength>,maxLength=<maxLength>)"`
*
* @example
* ```ts
* TStringOfLength({ minLength: 5 }).isValid("1234"); // false
* TStringOfLength({ minLength: 5 }).isValid("123456789"); // true
* TStringOfLength({ minLength: 5 }).name === "string(minLength=5)"; // true
* ```
*/
export default function TStringWithLength(options: {
minLength?: number;
maxLength?: number;
}) {
let name = "string";
const isOptionEmpty =
options.minLength === undefined && options.maxLength === undefined;
if (!isOptionEmpty) name += "(";
if (options.minLength !== undefined) name += `minLength=${options.minLength}`;
if (options.minLength !== undefined && options.maxLength !== undefined)
name += ",";
if (options.maxLength !== undefined) name += `maxLength=${options.maxLength}`;
if (!isOptionEmpty) name += ")";
return TValidate<string>(
name,
(value) =>
typeof value === "string" &&
isByteLength(value, { min: options.minLength, max: options.maxLength })
);
}