DEV Community

Alexander Nitrovich
Alexander Nitrovich

Posted on • Originally published at blog.eurovalidate.com

Validate EU VAT in Kotlin

As modern businesses expand across Europe, verifying EU VAT numbers is vital to ensure compliance, fraud prevention, and accurate billing. Kotlin, renowned for its expressiveness and seamless Java interoperability, makes an excellent choice for backend services. In this guide, you'll learn how to implement EU VAT validation using Kotlin by leveraging API integration, with practical examples provided throughout.

Understanding EU VAT Validation

EU VAT numbers are structured variably across member states, typically consisting of a country code followed by numeric or alphanumeric characters. Validation checks include verifying the format and ensuring the number's legitimacy. Challenges arise from the diversity in VAT formats and rules, making a third-party API an attractive solution. Using an API centralizes validation logic, ensuring accuracy and compliance updates without client-side overhauls.

Setting Up Your Kotlin Environment

To get started, ensure you have Kotlin installed and set up with your preferred build system, such as Gradle or Maven. For a new Kotlin project, initialize it using:

gradle init --type kotlin-application
Enter fullscreen mode Exit fullscreen mode

Configure your dependencies in the build.gradle.kts file and ensure you're prepared to make HTTP requests, potentially using libraries like khttp.

Implementing VAT Validation in Kotlin

Starting with basic VAT format checks can be accomplished using simple regular expressions in Kotlin:

val vatRegex = Regex("^[A-Z]{2}[0-9A-Z]{8,12}\$")
fun isValidVatFormat(vatNumber: String): Boolean {
    return vatRegex.matches(vatNumber)
}

fun main() {
    val vatNumber = "NL820646660B01"
    println("Is VAT valid? ${isValidVatFormat(vatNumber)}")
}
Enter fullscreen mode Exit fullscreen mode

This regex covers the general EU VAT number structure, acting as a first line of validation defense.

Integrating Developer-First API for VAT Verification

Transform your application by connecting it to the EuroValidate API. This integration allows you to offload complicated VAT logic and leverage their accurate validation service.

First, obtain your API key from EuroValidate and incorporate the API call using a Kotlin-friendly HTTP client:

import khttp.get

fun validateVatViaApi(vatNumber: String, apiKey: String): String {
    val response = get(
        url = "https://api.eurovalidate.com/v1/vat/$vatNumber",
        headers = mapOf("Authorization" to "Bearer $apiKey")
    )

    return if (response.statusCode == 200) {
        response.jsonObject.getString("status")
    } else {
        "Validation failed with status: ${response.statusCode}"
    }
}

fun main() {
    val vatNumber = "FR40303265045"
    val apiKey = "YOUR_API_KEY_HERE"
    println("API Validation Result: ${validateVatViaApi(vatNumber, apiKey)}")
}
Enter fullscreen mode Exit fullscreen mode

This snippet demonstrates API integration, ensuring comprehensive validation with added metadata such as company details and request insights.

Valid vs. Invalid API Responses

A successful API request confirms the VAT number with details:

  • Valid VAT Response Example:
  {
      "vat_number": "NL820646660B01",
      "country_code": "NL",
      "status": "valid",
      "company_name": "Company X",
      "company_address": "Street X, Amsterdam",
      "request_id": "abc123",
      "meta": {
          "confidence": "high",
          "source": "EU database",
          "cached": false,
          "response_time_ms": 123
      }
  }
Enter fullscreen mode Exit fullscreen mode
  • Invalid VAT Response Example:
  {
      "vat_number": "DE89370400440532013000",
      "country_code": "DE",
      "status": "invalid",
      "request_id": "abc124",
      "meta": {
          "confidence": "low",
          "source": "EU database",
          "cached": false,
          "response_time_ms": 150
      }
  }
Enter fullscreen mode Exit fullscreen mode

Code Examples and Walkthrough

Below is a Kotlin function that combines format checking and API validation with error handling:

fun validateVat(vatNumber: String, apiKey: String): String {
    return if (!isValidVatFormat(vatNumber)) {
        "Invalid VAT format"
    } else {
        try {
            validateVatViaApi(vatNumber, apiKey)
        } catch (e: Exception) {
            "Error during validation: ${e.message}"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, initial regex validation is followed by API verification. This order reduces unnecessary API calls, optimizing performance and cost.

Testing and Debugging Your VAT Validator

Testing is crucial. Implement unit tests for format validation and mock API interactions for integration testing:

fun testValidVatFormat() {
    assert(isValidVatFormat("NL820646660B01"))
}

fun testInvalidVatFormat() {
    assert(!isValidVatFormat("INVALIDVAT"))
}
Enter fullscreen mode Exit fullscreen mode

Use Kotlin's build-in assertions and consider frameworks like JUnit for comprehensive testing.

Conclusion and Next Steps

Through effective use of Kotlin and a powerful API, VAT validation can be streamlined, enhancing compliance and operational efficiency. Embrace these code snippets and integrate the EuroValidate API into your projects.

Ready to streamline your VAT validations? Sign up for our free API key today and see how our API can simplify your compliance workflow. For detailed API documentation, visit EuroValidate API Docs.

Join our community, subscribe to our newsletter for more Kotlin tips, and start maximizing your application's potential with EuroValidate!

Top comments (0)