Skip to main content
AllDevToolsHub
Back to all patterns

MIME Type Validation

Validation

Validates MIME type strings like text/html, application/json, image/png.

/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_.+]*$/

How it works

MIME types consist of a type and subtype separated by a slash. Both type and subtype can contain letters, digits, and certain special characters. This pattern validates the basic structure per RFC 2045.

Test Cases

Should Match

  • text/html
  • application/json
  • image/png
  • application/vnd.api+json

Should NOT Match

  • text
  • /html
  • text/
  • text html

Quick Summary

Validates MIME type strings (type/subtype) per RFC 2045. Matches common types like text/html, application/json, and vendor types like application/vnd.api+json.

Key Takeaways

Key Takeaways

  • Format: type/subtype, both parts required
  • Allows letters, digits, and special characters in both type and subtype
  • Does not validate against the IANA MIME type registry, unknown types pass
  • Parameters (e.g., charset=utf-8) are not matched, strip them before validating
Use Cases

When to use it

  • Validating Content-Type header values in API middleware
  • Checking MIME types in file upload handlers
  • Parsing Accept header values in content negotiation
Watch out

Common Mistakes

  • Not stripping parameters before validating, text/html; charset=utf-8 will not match
  • Assuming any matching MIME type is safe, always whitelist expected types
FAQ

MIME Type Validation, Frequently Asked

How do I get the MIME type of a file in Node.js?

Use the 'mime-types' package: mime.lookup('file.png') returns 'image/png'.

What is the difference between Content-Type and Accept headers?

Content-Type describes the format of the request/response body. Accept lists the formats the client can handle.