-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathvalidation.ts
More file actions
47 lines (38 loc) · 1.79 KB
/
Copy pathvalidation.ts
File metadata and controls
47 lines (38 loc) · 1.79 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
export class WidgetValidationError extends Error {
name = "Widget Validation Error"
constructor(message: string) {
super(message)
}
}
/**
* Asserts that the given input string only contains the characters specified by `legalCharacters`.
* @param input The string under test
* @param legalCharacters The characters that the input string may contain. Follows character class notation from regex (inside the [])
* @param message The message that is included in the error. Specify where the input is used and can be corrected.
* @throws WidgetValidationError If the input contains characters not allowed by legalCharacters
*/
export function throwOnIllegalChars(input: string, legalCharacters: string, message: string): void {
const pattern = new RegExp(`([^${legalCharacters}])`, "g")
const illegalChars = input.match(pattern);
if (illegalChars === null) {
return
}
const formatted = illegalChars
.reduce((unique, c) => unique.includes(c) ? unique : [...unique, c], [] as string[])
.map(c => `"${c}"`)
.join(", ");
throw new WidgetValidationError(`${message} contains illegal characters ${formatted}. Allowed characters are [${legalCharacters}].`)
}
/**
* Asserts that the given input string matches the given pattern.
* @param input The string under test
* @param pattern The pattern the input must match
* @param message The message that is included in the error. Specify where the input is used and can be corrected.
* @throws WidgetValidationError If the input contains characters not allowed by legalCharacters
*/
export function throwOnNoMatch(input: string, pattern: RegExp, message: string) {
if (pattern.test(input)) {
return
}
throw new WidgetValidationError(`${message} does not match the pattern ${pattern}.`)
}