求用于验证Cloudinary Public ID的JavaScript正则表达式
Cloudinary Public ID Validation Regex in JavaScript
Let's nail this regex for validating Cloudinary Public IDs! First, let's recap the exact rules we need to enforce:
- All printable characters are allowed except the reserved characters:
? & # \ % < > . - Cannot start or end with a space (
) or slash (/)
Why Your Original Regex Failed
Your initial attempt ^[^\s\\]+[^?&#\%<>]+$ had a few key issues:
- You used HTML entities like
&instead of raw characters (&) — regex doesn't parse HTML entities - It didn't exclude the reserved character
. - It didn't account for the "no slash at start/end" rule
- The structure required at least two characters, which misses valid single-character Public IDs
The Correct Regex
Here's a regex that covers all the requirements, with clear logic:
const cloudinaryPublicIdRegex = /^(?![\s/])(?!.*[\s/]$)(?!.*[\?&#\\%<>.]).+$/;
Breakdown of the Regex
Let's break down each part to understand how it works:
^(?![\s/]): Ensures the string doesn't start with a space or slash(?!.*[\s/]$): Makes sure the string doesn't end with a space or slash(?!.*[\?&#\\%<>.]: Checks that no reserved characters appear anywhere in the string.+: Requires at least one character (since empty Public IDs aren't valid)
Test Cases
Let's verify with some examples:
- ✅ Valid:
my-profile_photo、blog/posts summer-vacation、custom-id!@$ - ❌ Invalid:
my-id(starts with space)、photos/(ends with slash)、image?.png(contains?)、file.name(contains.)
Alternative Concise Version
If you prefer a more compact regex without lookaheads (though slightly less readable), you can use this:
const cloudinaryPublicIdRegex = /^[^\s/?&#\\%<>](?:[^\?&#\\%<>]*[^\s/?&#\\%<>])?$/;
This works by:
- Matching a valid start character (not space, slash, or reserved)
- Allowing any number of non-reserved characters in the middle
- Ending with a valid character (same rules as the start)
- The
?makes the middle+end part optional, supporting single-character IDs
内容的提问来源于stack exchange,提问作者steve-o
相关产品推荐
相关产品推荐

