Address Validation

Validate Address Format

Using validateAddress()

The validateAddress() method verifies whether an address is valid for a given network and identifies its type. This is useful for input validation before performing operations that require specific address formats.

The method accepts an address string or Address object along with the target network configuration. It returns an AddressTypes value indicating the address type, or null if the address is invalid.

Method Signature

typescript
validateAddress() signature
validateAddress(
    addr: string | Address,
    network: Network
): AddressTypes | null

Address Types Enum

typescript
Address Types Enum
enum AddressTypes {
    P2PKH = 'P2PKH',                             // Legacy address (1...)
    P2OP = 'P2OP',                               // OPNet contract address
    P2SH_OR_P2SH_P2WPKH = 'P2SH_OR_P2SH-P2WPKH', // Script hash (3...)
    P2PK = 'P2PK',                               // Public key
    P2TR = 'P2TR',                               // Taproot (bc1p...)
    P2MR = 'P2MR',                               // Pay-to-Merkle-Root / BIP 360 (bc1z...)
    P2WPKH = 'P2WPKH',                           // Native SegWit (bc1q...)
    P2WSH = 'P2WSH',                             // SegWit script hash
    P2WDA = 'P2WDA',                             // UNUSED - internal only
}

Validate Address Format

typescript
Validate address format
import { JSONRpcProvider } from 'opnet';
import { networks, Address } from '@btc-vision/bitcoin';

const network = networks.regtest;
const provider = new JSONRpcProvider({ url: 'https://regtest.opnet.org', network });

const addressType = provider.validateAddress(
    'bc1p...address...',
    network
);

if (addressType === null) {
    console.log('Invalid address');
} else {
    console.log('Address type:', addressType);
}