diff --git a/lib/jsonschema.lua b/lib/jsonschema.lua index dc1f7ed..aed9c95 100644 --- a/lib/jsonschema.lua +++ b/lib/jsonschema.lua @@ -943,7 +943,7 @@ generate_validator = function(ctx, schema) end if schema.pattern then ctx:stmt(sformat(' if not %s(%s, %q) then', ctx:libfunc('custom.match_pattern'), ctx:param(1), schema.pattern)) - ctx:stmt(sformat(' return false, %s([[failed to match pattern %q with %%q]], %s)', ctx:libfunc('string.format'), schema.pattern, ctx:param(1))) + ctx:stmt(sformat(' return false, %s([[failed to match pattern %q with %%q]], %s)', ctx:libfunc('string.format'), string.gsub(schema.pattern, "%%", "%%%%"), ctx:param(1))) ctx:stmt( ' end') end ctx:stmt('end') -- if string diff --git a/t/default.lua b/t/default.lua index dedfce2..4a3508e 100644 --- a/t/default.lua +++ b/t/default.lua @@ -213,3 +213,23 @@ for i, case in ipairs(cases) do assert(ok, string.format("fail: validate case %d, err: %s, ", i, err)) end ngx.say("passed: check string len") + +----------------------------------------------------- test case 8 +-- test pattern with `%` +local host_pattern = [[^http(s)?:\/\/[a-zA-Z0-9-_.:\@%]+$]] +local rule = { + type = "object", + properties = { + foo = { + pattern = host_pattern, + }, + }, +} + +local validator = jsonschema.generate_validator(rule) +local t = { + foo = "http://#baidu.com" +} +local ok, err = validator(t) +assert(ok~=nil, ("pattern: failed to check pattern with `%%`: %s"):format(err)) +ngx.say("passed: pass check pattern with `%`")