场景描述
需要对字符串做限制,只能使用 a 至 z,0 至 9 和连字符-。因为 solidity 内没有正则表达式,所以只能逐个判断。
代码如下
pragma solidity ^0.8;
/// @notice Validates that a domain name is composed only from characters in the allowed character set:
/// - the lowercase letters `a-z`
/// - the digits `0-9`
/// - the hyphen `-`
/// @dev This function allows empty (zero-length) domains. If this should not be allowed,
/// make sure to add a respective check when using this function in your code.
/// @param domain The name.
/// @return `true` if the name is valid or `false` if at least one char is invalid.
/// @dev Aborts on the first invalid char found.
function isDdomainValid(string calldata domain) pure returns (bool) {
bytes calldata nameBytes = bytes(domain);
uint256 nameLength = nameBytes.length;
for (uint256 i; i < nameLength; i++) {
uint8 char = uint8(nameBytes[i]);
// if char is between a-z
if (char > 96 && char < 123) {
continue;
}
// if char is between 0-9
if (char > 47 && char < 58) {
continue;
}
// if char is -
if (char == 45) {
continue;
}
// invalid if one char doesn't work with the rules above
return false;
}
return true;
}