startsWith And endsWith Validate Input Rules
Validate names against suffix and prefix rules with endsWith and startsWith, handling extension allowlists and reserved-name prefixes.
Code
const uploads = ['photo.jpg', 'archive.tar.gz', 'notes.txt', 'PHOTO.JPG'];
const allowed = ['.jpg', '.png'];
for (const name of uploads) {
// endsWith checks the suffix; case differences matter for extensions
const ok = allowed.some((ext) => name.toLowerCase().endsWith(ext));
console.log(name, ok ? 'accepted' : 'rejected');
}
// startsWith checks the prefix, e.g. reserved names or required tags
const reserved = ['test-', 'tmp-'];
for (const name of ['tmp-scratch', 'main-app']) {
const blocked = reserved.some((prefix) => name.startsWith(prefix));
console.log(name, blocked ? 'reserved prefix' : 'free prefix');
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
photo.jpg accepted
archive.tar.gz rejected
notes.txt rejected
PHOTO.JPG accepted
tmp-scratch reserved prefix
main-app free prefixHow it works
Two loops stack here: for (const name of uploads) selects, for (const name of ['tmp-scratch', 'main-app']) processes.
The file’s state is a handful of top-level bindings: uploads, allowed, reserved.
Watch out for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Core lines
const ok = allowed.some((ext) => name.toLowerCase().endsWith(ext));
const blocked = reserved.some((prefix) => name.startsWith(prefix));
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `uploads`, `allowed`, `reserved`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.