Skip to main content

Overview

Always validate phone numbers before submitting internet top-up orders. This prevents errors, reduces refunds, and improves user experience by catching format issues immediately.
Critical Step: Validation prevents 90% of order failures. Never skip this step.

API Reference

GET /v3/internet/check-number

Complete endpoint documentation

Phone Number Formats

  • ADSL
  • 4G LTE
Pattern: ^0[0-9]{8}$Description: 9 digits starting with 0Valid Examples:
  • 036362608
  • 031417237
  • 021123456
Invalid Examples:
  • 36362608 - Missing leading zero
  • 0363626081 - Too long (10 digits)
  • 213636362608 - Wrong format (has country code)
  • +213636362608 - Wrong format (has +)

Basic Validation

async function validateInternetNumber(type, number) {
  const response = await fetch(
    `https://api.oneclickdz.com/v3/internet/check-number?type=${type}&number=${number}`,
    {
      headers: {
        "X-Access-Token": process.env.API_KEY,
      },
    }
  );

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }

  const result = await response.json();
  return result.data;
}

// Usage
try {
  await validateInternetNumber('ADSL', '036362608');
  console.log('✅ Number is valid');
} catch (error) {
  console.error('❌ Validation failed:', error.message);
}

Client-Side Format Validation

Validate format client-side first for instant feedback:
function validateADSLFormat(number) {
  const pattern = /^0[0-9]{8}$/;
  return pattern.test(number);
}

function validate4GFormat(number) {
  const pattern = /^213[0-9]{9}$/;
  return pattern.test(number);
}

function validateFormat(type, number) {
  if (type === 'ADSL') {
    return validateADSLFormat(number);
  } else if (type === '4G') {
    return validate4GFormat(number);
  }
  return false;
}

// Usage
const number = '036362608';
const type = 'ADSL';

if (!validateFormat(type, number)) {
  console.error('Invalid format. Please check the number.');
} else {
  // Format is correct, now validate with API
  await validateInternetNumber(type, number);
}

Complete Validation Flow

async function validateCompleteFlow(type, number) {
  // Step 1: Validate service type
  if (!['ADSL', '4G'].includes(type)) {
    return {
      valid: false,
      error: 'INVALID_TYPE',
      message: 'Service type must be ADSL or 4G'
    };
  }

  // Step 2: Client-side format check
  if (!validateFormat(type, number)) {
    return {
      valid: false,
      error: 'INVALID_FORMAT',
      message: type === 'ADSL' 
        ? 'ADSL numbers must be 9 digits starting with 0 (e.g., 036362608)'
        : '4G numbers must be 12 digits starting with 213 (e.g., 213665983439)'
    };
  }

  // Step 3: API validation
  try {
    await validateInternetNumber(type, number);
    return {
      valid: true,
      type,
      number
    };
  } catch (error) {
    return {
      valid: false,
      error: 'API_VALIDATION_FAILED',
      message: error.message
    };
  }
}

// Usage
const result = await validateCompleteFlow('ADSL', '036362608');

if (!result.valid) {
  console.error(`Validation failed: ${result.message}`);
} else {
  console.log('✅ Ready to place order');
}

Validation Caching

Cache successful validations briefly to reduce API calls:
class ValidationCache {
  constructor(ttlSeconds = 300) { // 5 minutes
    this.cache = new Map();
    this.ttl = ttlSeconds * 1000;
  }

  async validate(type, number) {
    const key = `${type}:${number}`;
    const cached = this.cache.get(key);
    const now = Date.now();

    // Return cached if valid
    if (cached && (now - cached.timestamp) < this.ttl) {
      return cached.result;
    }

    // Validate with API
    try {
      const result = await validateInternetNumber(type, number);
      this.cache.set(key, {
        result: { valid: true, ...result },
        timestamp: now,
      });
      return { valid: true, ...result };
    } catch (error) {
      // Don't cache failures
      throw error;
    }
  }

  invalidate(type, number) {
    const key = `${type}:${number}`;
    this.cache.delete(key);
  }
}

// Usage
const validationCache = new ValidationCache(300); // 5 minutes

// First call - validates with API
const result1 = await validationCache.validate('ADSL', '036362608');

// Second call within 5 minutes - returns cached
const result2 = await validationCache.validate('ADSL', '036362608');

User-Friendly Error Messages

Provide clear feedback based on error type:
function getValidationErrorMessage(type, error) {
  const messages = {
    INVALID_TYPE: 'Please select either ADSL or 4G service type.',
    
    INVALID_FORMAT: {
      ADSL: 'Please enter a valid ADSL number (9 digits starting with 0).\nExample: 036362608',
      '4G': 'Please enter a valid 4G number (12 digits starting with 213).\nExample: 213665983439'
    },
    
    API_VALIDATION_FAILED: {
      default: 'This number is not valid for the selected service type.',
      'ERR_PHONE': 'This number cannot be used for internet recharge.'
    }
  };
  
  if (error === 'INVALID_FORMAT') {
    return messages.INVALID_FORMAT[type];
  }
  
  if (error === 'API_VALIDATION_FAILED') {
    return messages.API_VALIDATION_FAILED.default;
  }
  
  return messages[error] || 'Unable to validate number. Please try again.';
}

Best Practices

Validate Early

Check format client-side before API call

Clear Messages

Show specific, helpful error messages

Cache Results

Cache valid numbers for 5 minutes

Visual Feedback

Show real-time validation status as user types

Testing Validation

async function testValidation() {
  const testCases = [
    // ADSL tests
    { type: 'ADSL', number: '036362608', expected: true },
    { type: 'ADSL', number: '031417237', expected: true },
    { type: 'ADSL', number: '36362608', expected: false },  // Missing 0
    { type: 'ADSL', number: '0363626081', expected: false }, // Too long
    
    // 4G tests
    { type: '4G', number: '213665983439', expected: true },
    { type: '4G', number: '213472731602', expected: true },
    { type: '4G', number: '0665983439', expected: false },   // Wrong format
    { type: '4G', number: '+213665983439', expected: false }, // Has +
  ];

  console.log('🧪 Testing validation...\n');

  for (const test of testCases) {
    const result = await validateCompleteFlow(test.type, test.number);
    const passed = result.valid === test.expected;
    
    console.log(
      `${passed ? '✅' : '❌'} ${test.type} ${test.number}: ${result.valid ? 'VALID' : 'INVALID'}`
    );
    
    if (!passed) {
      console.log(`  Expected: ${test.expected}, Got: ${result.valid}`);
      if (!result.valid) {
        console.log(`  Error: ${result.message}`);
      }
    }
  }
}

Next Steps