Solidity – String Validation for Alpha Numeric and Length

soliditystring

What is best practice in solidity for testing that an input string contains only alpha numeric characters and is not longer then x amount of chars?

   function testStr(string str) constant returns (bool){
        bytes memory b = bytes(str);
        if(b.length > 13) return false;

        for(uint i; i < b.length; i++){
            //test if is tring only contains 1234567890abcdefghijklmnopqrstuvwxyz and . char

        }

        return true;
    }

Best Answer

You can use the ASCII codes to do so:

function testStr(string str) public pure returns (bool){
    bytes memory b = bytes(str);
    if(b.length > 13) return false;

    for(uint i; i<b.length; i++){
        bytes1 char = b[i];

        if(
            !(char >= 0x30 && char <= 0x39) && //9-0
            !(char >= 0x41 && char <= 0x5A) && //A-Z
            !(char >= 0x61 && char <= 0x7A) && //a-z
            !(char == 0x2E) //.
        )
            return false;
    }

    return true;
}
Related Topic