Question
How do I check if a base64 string is valid before decoding it?
Asked by: USER7136
62 Viewed
62 Answers
Answer (62)
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.