4

Does anyone know of a jQuery plugin that can check if text is base64 encoded by chance? I want to be able to decode base64 strings but only if the string is encoded to begin with. I see several scripts out there that can encode and decode but I really one that can check if the string is encoded.

Does such a thing exist?

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
Nick
  • 19,198
  • 51
  • 185
  • 312
  • Related Q: http://stackoverflow.com/questions/3355407/validate-string-is-base64-format-using-regex#3355534 – Incognito Aug 19 '11 at 20:17
  • 1
    Does this answer your question? [RegEx to parse or validate Base64 data](https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data) – Wiktor Stribiżew Jan 11 '22 at 09:51

4 Answers4

11

Must it really be a jQuery plugin? Just use a simple JavaScript regex match:

var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");

// ...

if (base64Matcher.test(someString)) {
    // It's likely base64 encoded.
} else {
    // It's definitely not base64 encoded.
}

The regex pattern is taken from this question: RegEx to parse or validate Base64 data.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
4

The above answer didn't count for the padding with equals signs (= or ==) at the end of the string for me. I've updated the query and the following works for me.

var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$");

Branndon
  • 505
  • 3
  • 21
2

I know this might be late to answer but this is what I came up so far. In this case, I use the {match} in jQuery. This is applicable for images or texts. Hope this helps

var sSampleBase64Text = 'data:text/plain;base64,MSkgTG9naW4gRGV0YWlscwogPj4gdGNfYWRtaW5fYXllZQogPj4gdHdpbmtsZXMyMnRo';
var mCheckMatchResult = sSampleBase64Text.match(/^(?:[data]{4}:(text|image|application)\/[a-z]*)/);

var sAlertMessage = 'Valid base 64 encode string';
if (mCheckMatchResult === null || mCheckMatchResult.length <= 0) {
     sAlertMessage = 'Not a valid base 64 encode string';
} 

$('.result').append('<p>' + sAlertMessage + '</p>');

Try to look this up here: https://jsfiddle.net/lajatomary/a8tugwe3/4/

Marylyn Lajato
  • 1,171
  • 1
  • 10
  • 15
0

Just encountered this and found a solution that might be helpful:

function safeBase64Encode(testString) {
  try {
    // If it's encoded, it will look the same in atob(btoa()) and btoa(atob())
    let isEncoded = btoa(atob(testString)) == atob(btoa(testString))
    if ( isEncoded ) {
      return testString
      }
  } catch (err) {
    // If we get an error like it's not a valid encoding, you gotta encode it.
    return btoa(testString)
  }
}
bubthegreat
  • 301
  • 1
  • 9