-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathpattern.ts
More file actions
56 lines (52 loc) · 1.63 KB
/
pattern.ts
File metadata and controls
56 lines (52 loc) · 1.63 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
48
49
50
51
52
53
54
55
56
import { Keyword, JsonSchemaValidatorParams } from "../Keyword";
import { SchemaNode } from "../SchemaNode";
import settings from "../settings";
const KEYWORD = "pattern";
const { REGEX_FLAGS } = settings;
export const patternKeyword: Keyword<"pattern"> = {
id: KEYWORD,
keyword: KEYWORD,
parse: parsePattern,
addValidate: (node) => node[KEYWORD] != null,
validate: validatePattern
};
function parsePattern(node: SchemaNode) {
const pattern = node.schema[KEYWORD];
if (pattern == null) {
return;
}
if (typeof pattern !== "string") {
return node.createError("schema-error", {
pointer: node.schemaLocation,
schema: node.schema,
value: pattern,
message: `Keyword 'pattern' must be a string - received '${typeof pattern}'`
});
}
try {
node[KEYWORD] = new RegExp(pattern, node.schema.regexFlags ?? REGEX_FLAGS);
} catch (e) {
return node.createError("schema-error", {
pointer: node.schemaLocation,
schema: node.schema,
value: pattern,
message: (e as Error).message
});
}
}
function validatePattern({ node, data, pointer = "#" }: JsonSchemaValidatorParams<"pattern">) {
if (typeof data !== "string") {
return;
}
if (node.pattern.test(data) === false) {
const { schema } = node;
return node.createError("pattern-error", {
pattern: schema.pattern,
description: schema.patternExample || schema.pattern,
received: data,
schema,
value: data,
pointer
});
}
}