Search code examples
base64

How to check whether a string is Base64 encoded or not


I want to decode a Base64 encoded string, then store it in my database. If the input is not Base64 encoded, I need to throw an error.

How can I check if a string is Base64 encoded?


Solution

  • You can use the following regular expression to check if a string constitutes a valid base64 encoding:

    ^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$
    

    In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /]. If the rest length is less than 4, the string is padded with '=' characters.

    ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

    ([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$ means the string ends in one of three forms: [A-Za-z0-9+/]{4}, [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==.