I wanted to do something similar, and ended up Googling it and found nothing, so I made my own base64 validator:
function isBase64(text) {
let utf8 = Buffer.from(text).toString("utf8");
return !(/[^\x00-\x7f]/.test(utf8));
}
This isn't great, because I used it for a different purpose but you may be able to build on it, here is an example using atob
to prevent invalid base64 chars (they are ignored otherwise):
function isBase64(text) {
try {
let utf8 = atob(text);
return !(/[^\x00-\x7f]/.test(utf8));
} catch (_) {
return false;
}
}
Now, about how it works:
Buffer.from(text, "base64")
removes all invalid base64 chars from the string, then converts the string to a buffer, toString("utf8")
, converts the buffer to a string. atob
does something similar, but instead of removing the invalid chars, it will throw an error when it encounters one (hence the try...catch
).
!(/[^\x00-\x7f]/.test(utf8))
will return true
if all the chars from the decoded string belong in the ASCII charset, otherwise it will return false
. This can be altered to use a smaller charset, for example, [^\x30-\x39\x41-\x5a\x61-\x7a]
will only return true
if all the characters are alphanumeric.