Skip to content

Error indicating parameter does not match regex shows wrong regex with backslashes escaped multiple times #429

@jmml97

Description

@jmml97

When using kin-openapi to validate query paramters if one of them fails the 'format' or 'pattern' validation an error is returned indicating that this is the case. This error includes a string representation of the regular expression that the parameter should conform to.

The problem is this string representation of the regular expression is wrong because escaped backslash \ characters appear escaped multiple times.

So for the 'date-time' format the regular expression the parameter must conform to is:

^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?(Z|(\+|-)[0-9]{2}:[0-9]{2})?$

Which as a Go string it has double backslashes \ in order to escape that character:

^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?(Z|(\\+|-)[0-9]{2}:[0-9]{2})?$

But the message that kin-openapi returns is:

parameter \"parameter\" in query has an error: string doesn't match the format \"date-time\" (regular expression \"^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?(Z|(\\\\+|-)[0-9]{2}:[0-9]{2})?$\")

There you can see the backslash appears four times. This does not represent the same regular expression that the parameter should conform to, as this means the string should have two consecutive backslashes in it.

I think the problem lies in the way the regular expression is printed in the message. The code uses the %q format specifier which takes the string and creates a 'golang-compliant' string. That means the supposed control characters are escaped in the string. So when the string with the already escaped backslash is printed with that format specifier, each backslash is escaped.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions