12

I am building an application which requires user to paste the transaction hash of a transaction. But i want a regex string i could pass to the pattern attribute of the input element that receives it to validate it. What is the general regexp that validates ethereum transaction hash?

3
  • Possible duplicate of How can I check if an Ethereum address is valid? Commented Dec 24, 2017 at 14:13
  • 3
    @RichardHorrocks It's not a duplicate; this question is about the transaction hash, not the address. I don't see a regex for the transaction hash in that answer.
    – Jesbus
    Commented Dec 24, 2017 at 14:16
  • Ah, sorry, you're right :-) I read "regex" and ignored everything else :-) Removed duplicate vote. Commented Dec 24, 2017 at 14:18

3 Answers 3

15

This regex should do the trick:

/^0x([A-Fa-f0-9]{64})$/

4
  • Keep in mind this only validates if the search contains only the right characters in the right length, not if a transaction exists on the blockchain.
    – Nick
    Commented Dec 24, 2017 at 17:38
  • @Nick this is clear. Thats just what i want
    – Oluwatumbi
    Commented Dec 25, 2017 at 15:04
  • 1
    I accepted the answer but i will rather go for /^(0x)?([A-Fa-f0-9]{64})$/ because it is also valid incase the source is from some of those who don't include the 0x prefix. Or do you think that should be considered invalid? The API i use to query the transactions accepts transaction IDs without the 0x
    – Oluwatumbi
    Commented Dec 25, 2017 at 15:06
  • How can we implement this in Python?
    – alper
    Commented Oct 8, 2021 at 17:35
2

As you didn't specify the technology you are using, I would suggest validating it against the go-ethereum hexutil https://github.com/ethereum/go-ethereum/blob/master/common/hexutil/hexutil.go#L60

Here's a simple example written in golang:

// IsValid : validates transaction with go-ethereum utils
func (model *Transaction) IsValid() bool {
    _, err := hexutil.Decode(model.Hash)
    return err == nil
}
2

btw, if you want to validate an address instead of a transaction, the following regex does it:

/^0x[a-fA-F0-9]{40}$/

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.