Determine if string is in base64 using JavaScript
If you want to check whether it can be decoded or not, you can simply try decoding it and see whether it failed:
try {
window.atob(str);
} catch(e) {
// something failed
// if you want to be specific and only catch the error which means
// the base 64 was invalid, then check for 'e.code === 5'.
// (because 'DOMException.INVALID_CHARACTER_ERR === 5')
}
Building on @anders-marzi-tornblad's answer, using the regex to make a simple true/false test for base64 validity is as easy as follows:
var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
base64regex.test("SomeStringObviouslyNotBase64Encoded..."); // FALSE
base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ="); // TRUE
Update 2021
- Following the comments below it transpires this regex-based solution provides a more accurate check than simply
try
`ingatob
because the latter doesn't check for=
-padding. According to RFC4648=
-padding may only be ignored for base16-encoding or if the data length is known implicitely. - Regex-based solution also seems to be the fastest as hinted by kai. As jsperf seems flaky atm i made a new test on jsbench which confirms this.
If "valid" means "only has base64 chars in it" then check against /[A-Za-z0-9+/=]/
.
If "valid" means a "legal" base64-encoded string then you should check for the =
at the end.
If "valid" means it's something reasonable after decoding then it requires domain knowledge.
This should do the trick.
function isBase64(str) {
if (str ==='' || str.trim() ===''){ return false; }
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}