limitLength.ts 1.0 KB

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