ajv-validator / ajv

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
https://ajv.js.org
MIT License
13.87k stars 877 forks source link

Getting "Invalid regular expression /<myRegex>/" error while compiling #2468

Closed abdulkerimawad closed 4 months ago

abdulkerimawad commented 4 months ago

What version of Ajv are you using? Does the issue happen if you use the latest version? Ajv version: 8.16.0

Ajv options object

    const ajv = new Ajv({ allErrors: true })

JSON Schema

    const schema: JSONSchemaType<jsonBodyType> = {
      "type": "object",
      "properties": {
        "description": {
          "type": "string",
          "pattern": /^{(\\"[a-zA-Z]+\\":\\"[a-zA-Z0-9/_,. &|$#*?\\n():%'!-]+\\")(,\\"[a-zA-Z]+\\":\\"[a-zA-Z0-9/_,. &|$#*?\\n():%'!-]+\\")*}$/.toString().slice(1, -1)
        },
      },
      "required": ["description"],
    }

Sample data

    {"description":"{\"en\":\"Unlock Samsung devices effortlessly with our FRP removal service. Bypass factory reset protection on the 
    latest models and Android versions. Take back control of your device now!\\n\\nQuickly check if your device is supported\"}"}

Your code

    const validate = ajv.compile(schema);
    validate(data);

Validation result, data AFTER validation, error messages

    node_modules\ajv\dist\core.js (23:38) @ defaultRegExp ⨯ SyntaxError: Invalid regular expression: /^{(\\"[a-zA-Z]+\\":\\"[a-zA-Z0- 
    9/_,. &|$#*?\\n():%'!-]+\\")(,\\"[a-zA-Z]+\\":\\"[a-zA-Z0-9/_,. &|$#*?\\n():%'!-]+\\")*}$/u: Lone quantifier brackets

image

What results did you expect? I expected the regex to be valid and the data to match it like in the RegExr website image

Are you going to resolve the issue? I don't know yet, I hope the ajv team resolves it

jasoniangreen commented 4 months ago

Hi there, there is something wrong with your regex and it is quite complicated so debugging it is difficult. It also doesn't help that you are using a non standard way to construct the regex. Please follow the instructions here - https://ajv.js.org/json-schema.html#pattern.

Basically AJV will take the string passed to pattern and pass it into new RegExp(your_pattern_string, "u"). So try constructing your regex using new RegExp with the "u" second param. If you can get that to succeed, then your schema will work with the same string. If you have trouble figuring out what's wrong, try starting with a simpler regex and build up to what you need, bit by bit.