validatePhoneNumber static method

bool validatePhoneNumber(
  1. String phoneNumber
)

Validates a phone number format for WhatsApp.

phoneNumber is the phone number to validate. Returns true if the phone number is valid. Throws MessageException if the phone number is invalid.

Implementation

static bool validatePhoneNumber(String phoneNumber) {
  // Basic validation: remove non-digits and check length
  final digits = phoneNumber.replaceAll(RegExp(r'[^\d+]'), '');

  // Phone number should have at least country code and 7 digits
  if (digits.length < 8) {
    throw MessageException.invalidRecipient(
      'Phone number is too short. It should include country code and at least 7 digits.',
    );
  }

  // Should start with + or country code
  if (!digits.startsWith('+') && !RegExp(r'^[1-9]').hasMatch(digits)) {
    throw MessageException.invalidRecipient(
      'Phone number should start with a + sign or a valid country code.',
    );
  }

  return true;
}