---
title: Always Validate Client Data Server-side
impact: CRITICAL
impactDescription: ensures input validation cannot be bypassed by attackers
tags: validation, server-side, input, sanitization, security, kotlin
---

## Always Validate Client Data Server-side

Client-side validation (browser or mobile apps) is for User Experience (UX) only. It can be easily bypassed using tools like Proxy, cURL, or Postman. All data entering the server must be strictly validated server-side.

**Incorrect (trusting client validation):**

```kotlin
// No server validation - trusting the mobile app
@PostMapping("/api/transfer")
fun transfer(@RequestBody data: TransferRequest): ResponseEntity<Any> {
    // amount could be negative or extremely large!
    transferService.execute(data.fromAccount, data.toAccount, data.amount)
    return ResponseEntity.ok(SuccessResponse())
}
```

**Correct (comprehensive server validation):**

```kotlin
import jakarta.validation.constraints.*

data class TransferRequest(
    @get:NotBlank val toAccount: String,
    @get:Positive @get:Max(1000000) val amount: Double
)

@PostMapping("/api/transfer")
fun transfer(@Valid @RequestBody data: TransferRequest): ResponseEntity<Any> {
    // 1. Data Format/Constraint validation (handled by @Valid)
    
    // 2. Business logic validation
    if (!accountService.exists(data.toAccount)) {
        throw AccountNotFoundException(data.toAccount)
    }
    
    // 3. Authorization validation
    if (!authService.canTransferFrom(currentUserId, data.fromAccount)) {
        throw AccessDeniedException("Unauthorized account access")
    }

    transferService.execute(data.fromAccount, data.toAccount, data.amount)
    return ResponseEntity.ok(SuccessResponse())
}
```

**Validation Strategies:**
- **JSR-303 / Bean Validation:** Use annotations like `@NotNull`, `@Size`, `@Pattern`, `@Min`, `@Max`.
- **Schema Validation:** Use libraries like `Konform` or `Kvalidation` if not using Spring.
- **Fail Fast:** Reject invalid data as early as possible in the request lifecycle.
- **Sanitization:** Strip dangerous characters (e.g., HTML tags if not expected) to prevent XSS.

**Tools:** Hibernate Validator, Konform (for Kotlin focus), SonarQube, Manual Security Audit
