In this section we'll check the validity of an EVM address using polkadot.js API dependencies
Checking the validity of a Substrate address using Polkadot utils
// Import Polkadot.js API dependencies.
const { decodeAddress, encodeAddress } = require('@polkadot/keyring');
const { hexToU8a, isHex } = require('@polkadot/util');
// Specify an address to test.
const addressToTest = 'testAddy';
// Function to check the validity of a Substrate address.
const isValidSubstrateAddress = (address) => {
try {
// Decode the address if it's in hex format, otherwise, assume it's a raw address.
const decodedAddress = isHex(address) ? hexToU8a(address) : decodeAddress(address);
// Encode the address to check its validity.
encodeAddress(decodedAddress);
return true;
} catch (error) {
return false;
}
};
// Call the function to check the validity of the specified address.
const isValid = isValidSubstrateAddress(addressToTest);
// Output the result.
console.log(`Is this Substrate address valid? ${isValid}`);