1

I need the (javascript) regex needed to validate a Cloudinary Public ID. The rules are:

The Public ID format supports all printable characters except for the following reserved characters: ? & # \ % < >. In addition, spaces and forward slashes (/) cannot be used as the first or last character of the Public ID.

Tried this but it's not working: ^[^\s\\]+[^?&#\%<>]+$

I was referencing these SO questions: Javascript regex - no white space at beginning + allow space in the middle and Regex - Does not contain certain Characters

steve-o
  • 1,303
  • 1
  • 14
  • 20
  • 2
    Can you provide us a few examples of the ID? – Gurmanjot Singh Jan 18 '18 at 15:47
  • I was only given one example: ufu6dphq8hhos0kiyhtx – steve-o Jan 18 '18 at 15:56
  • You forgot to take in account your second condition regarding the end of the ID. You need to add to the end of the regex (before the `$`): `[^\s\\]+`. In addition, you need to escape the "\" inside the unaccepted characters. – GalAbra Jan 18 '18 at 15:58
  • @GalAbra You're right, but unfortunately I couldn't even get past the first part of putting together the "no ^?\%<> characters" with "no spaces at the beginning". – steve-o Jan 18 '18 at 16:00
  • @steve-o I've edited my comment - you need to escape the "\" with "\\" – GalAbra Jan 18 '18 at 16:01

1 Answers1

2

Try this regex:

^(?![ \/])(?!.*[ \/]$)(?!.*[?&#\%<>])[ -~]+$

Click for Demo

Explanation:

  • ^ - asserts the start of the string
  • (?![ \/]) - negative lookahead to validate that the neither a space nor a / is at the start of the string
  • (?!.*[ \/]$) - negative lookahead to validate that the neither a space nor a / is at the end of the string
  • (?!.*[?&#\%<>]) - negative lookahead to make sure that none of these characters are found in the string [?&#\%<>]
  • [ -~]+ - matches 1+ occurrences of printable ascii characters(space to ~)
  • $ - asserts the end of the string
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43