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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With