-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathmaxLength.ts
More file actions
47 lines (43 loc) · 1.33 KB
/
maxLength.ts
File metadata and controls
47 lines (43 loc) · 1.33 KB
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
43
44
45
46
47
import ucs2decode from "../utils/punycode.ucs2decode";
import { Keyword, JsonSchemaValidatorParams } from "../Keyword";
import { SchemaNode } from "../SchemaNode";
import { isNumber } from "../types";
const KEYWORD = "maxLength";
export const maxLengthKeyword: Keyword<"maxLength"> = {
id: KEYWORD,
keyword: KEYWORD,
parse: parseMaxLength,
addValidate: (node) => node[KEYWORD] != null,
validate: validateMaxLength
};
function parseMaxLength(node: SchemaNode) {
const max = node.schema[KEYWORD];
if (max == null) {
return;
}
if (!isNumber(max)) {
return node.createError("schema-error", {
pointer: `${node.schemaLocation}/${KEYWORD}`,
schema: node.schema,
value: max,
message: `Keyword '${KEYWORD}' must be a number - received '${typeof max}'`
});
}
node[KEYWORD] = max;
}
function validateMaxLength({ node, data, pointer = "#" }: JsonSchemaValidatorParams<"maxLength">) {
if (typeof data !== "string") {
return;
}
const maxLength = node[KEYWORD];
const length = ucs2decode(data).length;
if (maxLength < length) {
return node.createError("max-length-error", {
maxLength: maxLength,
length,
pointer,
schema: node.schema,
value: data
});
}
}