Back to all patterns
Data URI Validation
Web & Network
Validates data URIs like data:image/png;base64, or data:text/plain,.
/^data:([a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]*)(;base64)?,/How it works
Data URIs embed file content directly in a URL. They start with data:, followed by a MIME type, an optional ;base64 flag, a comma, and the data. This pattern validates the header portion up to and including the comma.
Test Cases
Should Match
- data:image/png;base64,iVBORw0KGgo=
- data:text/plain,Hello
Should NOT Match
- https://example.com/image.png
- data:invalid
- data:,
Quick Summary
Validates the header portion of data URIs (data:mime/type;base64,). Capture group 1 is the MIME type. Does not validate the data payload itself.
Key Takeaways
Key Takeaways
- Format: data:[mediatype][;base64],<data>
- Capture group 1: the MIME type (e.g., image/png, text/plain)
- The ;base64 flag is optional, omitting it means the data is URL-encoded text
- Data URIs can be large, avoid using them for files over 32KB
Use Cases
When to use it
- Validating data URI inputs in image upload components
- Detecting data URIs in HTML or CSS for security scanning
- Extracting MIME type from a data URI before processing
Watch out
Common Mistakes
- Using data URIs for large files, they increase HTML/CSS size and cannot be cached separately
- Not validating the MIME type, accept only expected types (image/png, image/jpeg, etc.)
FAQ
Data URI Validation, Frequently Asked
Are data URIs safe to use in img src?
Yes, but validate the MIME type and size. Malicious data URIs can be used in XSS attacks if rendered as HTML.
How do I convert a file to a data URI in JavaScript?
Use FileReader.readAsDataURL(file) to get a base64 data URI from a File object.