How do I check if a base64 string is valid before decoding it?

Question

Grade: Education Subject: Support
How do I check if a base64 string is valid before decoding it?
Asked by:
62 Viewed 62 Answers

Answer (62)

Best Answer
(472)
You can use a regular expression to validate a base64 string before attempting to decode it. Here's a simple regex: ```javascript const base64Regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; if (base64Regex.test(base64String)) { // Proceed with decoding } ``` This regex checks if the string contains only valid base64 characters and ends with `=` if the length is a multiple of 4. It's a basic check and may not catch all invalid strings.