Jon*_*tan 25 javascript base64
我正在使用该window.atob('string')函数将字符串从base64解码为字符串.现在我想知道,有没有办法检查'string'实际上是否有效base64?如果字符串不是base64,我希望收到通知,以便我可以执行不同的操作.
pim*_*vdb 50
如果要检查它是否可以解码,您只需尝试解码它并查看它是否失败:
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')
}
Run Code Online (Sandbox Code Playgroud)
小智 27
这应该可以解决问题.
function isBase64(str) {
if (str ==='' || str.trim() ===''){ return false; }
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ton 20
如果"有效"表示"只有base64字符",则检查[A-Za-z0-9+/=].
如果"有效"表示"合法"base64编码的字符串,那么您应该检查=最后.
如果"有效"意味着它在解码后是合理的,那么它需要领域知识.
Phi*_*zen 19
在@ atornblad的答案的基础上,使用正则表达式对base64有效性进行简单的真/假测试就像下面这样简单:
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
Run Code Online (Sandbox Code Playgroud)
And*_*lad 18
我会使用正则表达式.试试这个:
/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
Run Code Online (Sandbox Code Playgroud)
说明:
^ # Start of input
([0-9a-zA-Z+/]{4})* # Groups of 4 valid characters decode
# to 24 bits of data for each group
( # Either ending with:
([0-9a-zA-Z+/]{2}==) # two valid characters followed by ==
| # , or
([0-9a-zA-Z+/]{3}=) # three valid characters followed by =
)? # , or nothing
$ # End of input
Run Code Online (Sandbox Code Playgroud)
小智 5
该方法尝试解码然后编码并与原始数据进行比较。还可以与引发解析错误的环境的其他答案结合起来。从正则表达式的角度来看,也可能有一个看起来像有效的 base64 的字符串,但不是实际的 base64。
if(btoa(atob(str))==str){
//...
}
Run Code Online (Sandbox Code Playgroud)
这是我最喜欢的验证库之一的完成方式:
const notBase64 = /[^A-Z0-9+\/=]/i;
export default function isBase64(str) {
assertString(str); // remove this line and make sure you pass in a string
const len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
const firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 ||
firstPaddingChar === len - 1 ||
(firstPaddingChar === len - 2 && str[len - 1] === '=');
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/chriso/validator.js/blob/master/src/lib/isBase64.js