1

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;
    }
2

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;
}
  • ok this seems solid and logical to do. I will test this when I have more time. – kasper Taeymans Jun 4 '18 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.