How to check whether a string is Base64 encoded or not

loganathan picture loganathan · Dec 20, 2011 · Viewed 258.8k times · Source

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?

Answer

xuanyuanzhiyuan picture xuanyuanzhiyuan · Dec 20, 2011

You can use the following regular expression to check if a string is base64 encoded or not:

^([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}==.