hack-json-schema icon indicating copy to clipboard operation
hack-json-schema copied to clipboard

Cannot validate 'pattern' that contains a forward slash

Open ryangreenberg opened this issue 5 years ago • 1 comments

Adding a pattern property to a schema is supposed to validate a value using the provided regular expression. This is done in generated code using StringPatternConstraint:

class StringPatternConstraint {
	public static function check(string $input, string $pattern, string $pointer): void {
		$match = \preg_match("/".$pattern."/", $input);
		/* ... */

However, this fails if $pattern contains a forward slash, because that collides with the / delimiter used here. A workaround is to use a double backslash when defining pattern in the schema so that it becomes \/ in the call to preg_match (this does change the meaning of the schema for other validators).

I thought that this was a case where we simply needed to use preg_quote, however that escapes all special characters in $pattern, not just the delimiter.

ryangreenberg avatar Oct 22 '19 04:10 ryangreenberg

https://www.php.net/manual/en/function.preg-quote.php:

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

delimiter If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

What we want is to escape the delimiter without also escaping other special chars. I think find/replace for /\/ might be sufficient, but I'm not sure if that breaks anything else.

ryangreenberg avatar Oct 22 '19 05:10 ryangreenberg