Validate Aptos account address in javascript

559 views Asked by At

I made an app that returns user assets from the Aptos blockchain. In the app, I have a form for the user's address. My goal is to validate that address using RegExp or something like that. I have this code:

const address = '0xcd30fbbda98b2aed026772c13e5ed90a7f056b589ef9e78cd96415e1af12451c';
function isValidAddress(address) { // code to check address }
console.log(isValidAddress(address));

I will appreciate any help.

2

There are 2 answers

0
Daniel Porteous On

It depends on your use case.

If you want to validate client side, you can try something like this:

import { TxnBuilderTypes } from "aptos";
import const { AccountAddress } = TxnBuilderTypes;

// Validate.
let accountAddress = AccountAddress.fromHex("0xcd30fbbda98b2aed026772c13e5ed90a7f056b589ef9e78cd96415e1af12451c");

// You can get it back as a string like this.
let accountAddressString = accountAddress.toHexString();

You can also try to validate using an Aptos node running the API (i.e. a fullnode). For example:

let client = AptosClient("https://fullnode.mainnet.aptoslabs.com");
client.getAccount("0xcd30fbbda98b2aed026772c13e5ed90a7f056b589ef9e78cd96415e1af12451c");

If the account exists, you'll get a 200 or if it doesn't, you'll get a 404. But if the account address was invalid, you'll get a 400 (bad request).

0
Daniel Porteous On

The above answer is for the legacy v1 SDK. You can do it with the v2 TS SDK like this:

import { AccountAddress } from "../../src";

function myFunction {
    let addr = "0x1";
 
    // Get an actual AccountAddress object.
    let accountAddress = AccountAddress.from(addr);

    // Just check if the account address is valid.
    let result = AccountAddress.isValid(addr);
    let valid = result.valid;
}

You can learn more about AccountAddress here: https://aptos-labs.github.io/aptos-ts-sdk/@aptos-labs/ts-sdk-1.9.1/classes/AccountAddress.html.