startsWith And endsWith Validate Input Rules

Validate names against suffix and prefix rules with endsWith and startsWith, handling extension allowlists and reserved-name prefixes.

JavascriptForm Validation

Code

javascriptsnippet
15 lines
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 prefix

How 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

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`.