1

consider this as an smart contract which check your eligiblity and i am creating multiple instances of the contract. require validation is done. but how can i make that minimum age value dynamic in the require statement. If user passed 30 age as minimum then in require error it should be "Minimum age should be 30 years". i dont want to hardcode that minimum age in reuqire, how can i achieve that?

contract checkMyEligibility {
    uint requiredAge;

    constructor(uint _requiredAge) {
        requiredAge = _requiredAge;
    }

    function checkAge(uint _age) public view {
        require(_age > requiredAge, "Minimum age should be 20 years");
        /*
        // like below line.
        require(_age > requiredAge,"Minimum age should be ${requiredAge} years");
        */
    } 
}
2
  • You want to make it so that:"Minimum age should be 20 years" Could change to: "Minimum age should be 30 years" To modify the message based on the requiredAge variable?
    – Sky
    Dec 9, 2022 at 8:31
  • 2
    Does this answer your question? How to concatenate strings in solidity? Dec 9, 2022 at 8:33

2 Answers 2

2

If you want to add parameters to the error message you have to use custom errors. For a detailed explanation see this post on Solidity Blog.

Basically you can add a custom error like this:

contract checkMyEligibility {
    error Underaged(uint256 givenAge, uint256 requiredAge);

    uint requiredAge;

    constructor(uint _requiredAge) {
       requiredAge = _requiredAge;
    }

    function checkAge(uint _age) public view {
      if (_age < requiredAge){
         revert Underaged({
             givenAge: _age,
             requiredAge: requiredAge
          });
        }
    }
}
0

I took a look in Solidity Documentation.

It is currently not possible to use custom errors in combination with require. Please use if (!condition) revert CustomError(); instead.

You can read more about it here:

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.