pattern.ts 961 B

12345678910111213141516171819202122232425262728
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type {KeywordCxt} from "../../compile/validate"
  3. import {usePattern} from "../code"
  4. import {_, str} from "../../compile/codegen"
  5. export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}>
  6. const error: KeywordErrorDefinition = {
  7. message: ({schemaCode}) => str`must match pattern "${schemaCode}"`,
  8. params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,
  9. }
  10. const def: CodeKeywordDefinition = {
  11. keyword: "pattern",
  12. type: "string",
  13. schemaType: "string",
  14. $data: true,
  15. error,
  16. code(cxt: KeywordCxt) {
  17. const {data, $data, schema, schemaCode, it} = cxt
  18. // TODO regexp should be wrapped in try/catchs
  19. const u = it.opts.unicodeRegExp ? "u" : ""
  20. const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema)
  21. cxt.fail$data(_`!${regExp}.test(${data})`)
  22. },
  23. }
  24. export default def