7

I want to validate a Base32 code before converting it. Is there a way to do this such as regular expression? I need to follow these standards by RFC 3548

Jacob Finamore
  • 748
  • 4
  • 18
  • @BreyndotEchse - With the difference being that base64 is padded to a 4-byte chunk and base32 is padded to an 8-byte chunk. Both get padded with `=`. **Edit:** The comment is gone, but here's the post it referred to: http://stackoverflow.com/a/475217/477563 – Mr. Llama Dec 08 '14 at 16:50

1 Answers1

4

This should do it:

^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=)?$

Demo

The (?:[A-Z2-7]{8})* part handles 40-bit sequences. The second part handles the final bytes as specified by the spec. Note that this pattern will accept an empty string too (0 bytes).

In PHP, use this with preg_match:

$isMatch = preg_match('#^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=)?$#', $input);
Lucas Trzesniewski
  • 47,154
  • 9
  • 90
  • 138