UNPKG

1.02 kBPlain TextView Raw
1import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {_, str, operators} from "../../compile/codegen"
4import {useFunc} from "../../compile/util"
5import ucs2length from "../../runtime/ucs2length"
6
7const error: KeywordErrorDefinition = {
8 message({keyword, schemaCode}) {
9 const comp = keyword === "maxLength" ? "more" : "fewer"
10 return str`must NOT have ${comp} than ${schemaCode} characters`
11 },
12 params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
13}
14
15const def: CodeKeywordDefinition = {
16 keyword: ["maxLength", "minLength"],
17 type: "string",
18 schemaType: "number",
19 $data: true,
20 error,
21 code(cxt: KeywordCxt) {
22 const {keyword, data, schemaCode, it} = cxt
23 const op = keyword === "maxLength" ? operators.GT : operators.LT
24 const len =
25 it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`
26 cxt.fail$data(_`${len} ${op} ${schemaCode}`)
27 },
28}
29
30export default def