javascriptvalidationbase32

How to check if a string is base32 encoded in javascript


I need to check if a geohash string is valid, so I need to check if it's a base32 or not.


Solution

  • Base32 uses A-Z and 2-7 for the encoding, and adds a padding character = to get a multiple of 8 characters, so you can create a regex to see if the candidate string matches.

    Using regex.exec a matching string will return the match information, a non-matching string will return null, so you can use an if to test whether a match is true or false.

    Base32 encodings also must always be a length that is a multiple of 8, and are padded with enough = chars to make it so; you can check the length is correct by using mod 8 --
    if (str.length % 8 === 0) { /* then ok */ }

    // A-Z and 2-7 repeated, with optional `=` at the end
    let b32_regex = /^[A-Z2-7]+=*$/;
    
    var b32_yes = 'AJU3JX7ZIA54EZQ=';
    var b32_no  = 'klajcii298slja018alksdjl';
        
    if (b32_yes.length % 8 === 0 &&
        b32_regex.exec(b32_yes)) {
        console.log("this one is base32");
    }
    else {
        console.log("this one is NOT base32");
    }
        
    if (b32_no % 8 === 0 &&
        b32_regex.exec(b32_no)) {
        console.log("this one is base32");
    }
    else {
        console.log("this one is NOT base32");
    }