What Is This?
This regex pattern validates standard Base64 encoded strings. Base64 encoding uses A-Z, a-z, 0-9, +, / characters and = for padding. The pattern ensures the string length is a multiple of 4 and padding (if present) is valid. For URL-safe Base64, use - instead of + and _ instead of /.
How to Use
The Pattern
Use this pattern to validate Base64 input before attempting to decode. This prevents decoding errors from malformed Base64 strings. The pattern handles all padding variants: no padding (length multiple of 4), single padding (ends with =), and double padding (ends with ==).
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/Examples
Valid Base64 strings
Matches: SGVsbG8gV29ybGQ= U29tZURhdGE= MTIzNDU2Nzg5MA== dGVzdA== Does not match: Invalid! base64!!! SGVsbG8gV29ybGQ
Various lengths
Matches: YQ== YWI= YWJj YWJjZA== Does not match: abc 12345 !!!!
Related Entries
More from this reference:
Email Address Validation
Validate email addresses with a standard pattern covering most common formats.
URL Pattern
Match HTTP and HTTPS URLs with optional port, path, query string, and fragment.
Phone Number (US/International)
Match US and international phone numbers with optional country code and separators.
Date (YYYY-MM-DD)
Match dates in ISO 8601 YYYY-MM-DD format with basic month and day validation.
Credit Card Number (Generic)
Match generic credit card numbers in grouped or continuous 16-digit format.
UUID v4
Match UUID v4 identifiers with the standard 8-4-4-4-12 hex format and version check.
Time (HH:MM 24-hour)
Match times in 24-hour HH:MM format with valid hour and minute ranges.
Frequently Asked Questions
Should I validate Base64 before decoding?
Yes. Validating before decoding prevents runtime errors from malformed input. However, validation does not guarantee the decoded result is meaningful — just that it is structurally valid Base64.
Does this pattern work for URL-safe Base64?
No. URL-safe Base64 uses - and _ instead of + and /. For URL-safe Base64, use: ^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=)?$. This is used in JWT tokens.