6

Why does the require not throw here when I am passing an empty string for the _name param?

function MyContract(bytes32 _name) public {
        require(_name.length > 0);
        name = _name;
    }

3 Answers 3

9

The bytes32 type is always exactly 32 bytes. Therefore, its length is always 32. It is unaware of whether it contains a string, number or something else.

I would recommend doing:

require(_name[0] != 0);

to verify that it does not represent an empty string.

4
  • 1
    Note: This only works for null-terminated strings.
    – Jesbus
    Commented Dec 16, 2019 at 18:32
  • Woudn't that return "false" is _name = "0x0000000000000000000000000000000000000000000000000000000000000001" since _name[0] = "0x00"? wouldn't it be better to do "require(_name > 0)" ? Commented May 17, 2022 at 7:16
  • If it's a null-terminated string and the first byte is 0x00 then the length of the string is 0 regardless of the content of the other bytes.
    – Jesbus
    Commented May 18, 2022 at 23:26
  • are hex numbers big endian in Solidity @AlbertoMolina?
    – Aaron Esau
    Commented Jul 12, 2022 at 20:09
2

I'm doing it like this:

require(_name != bytes32(0));

1

The solutions above are completely wrong! You can compare bytes32 and an empty string!

require(_name != "");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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