Lesson 82 of 158 – API Validation
82%

API Validation

API validation is the process of checking data received from a client before using it in the application or database. Validation helps ensure that API requests contain valid, complete, and correctly formatted data.

Note: Never trust data received from a mobile application. A React Native application can perform validation for a better user experience, but the server must always perform its own validation.

1. What is API Validation?

API validation checks whether incoming request data satisfies the rules required by the API.

React Native
     ↓
API Request
     ↓
Validate Data
     ↓
Valid?
  ↙     ↘
Yes      No
 ↓        ↓
Database  Error Response

2. Why is API Validation Important?

Without validation, invalid or incomplete data can be stored in the database.

For example, a student registration API may receive:

name = ""
email = "abc"
mobile = "123"

The API should reject this data if it does not satisfy the required rules.

3. Client-Side and Server-Side Validation

Client Validation Server Validation
Runs in React Native Runs on the server
Improves user experience Protects application data
Can be bypassed Must always be performed

4. Common Validation Rules

Common API validation rules include:

  • Required fields
  • Email format
  • Mobile number format
  • Minimum length
  • Maximum length
  • Numeric values
  • Allowed values
  • Date format
  • Password strength
  • Unique values

5. Required Field Validation

Suppose the API requires a student name.

$name = trim(
    $data['name'] ?? ''
);

if ($name === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Name is required"
    ]);

    exit;
}

6. Validate Multiple Required Fields

$name = trim(
    $data['name'] ?? ''
);

$email = trim(
    $data['email'] ?? ''
);

$mobile = trim(
    $data['mobile'] ?? ''
);

if (
    $name === '' ||
    $email === '' ||
    $mobile === ''
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "All fields are required"
    ]);

    exit;
}

7. Read JSON Request Data

A JSON API commonly receives data through the request body.

$data = json_decode(
    file_get_contents("php://input"),
    true
);

The second argument true converts the JSON object into a PHP associative array.

8. Validate JSON Input

$data = json_decode(
    file_get_contents("php://input"),
    true
);

if (!is_array($data)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid JSON data"
    ]);

    exit;
}

The API should not continue if the request body cannot be decoded into the expected structure.

9. Email Validation

PHP provides filter_var() for common email validation.

$email = trim(
    $data['email'] ?? ''
);

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid email address"
    ]);

    exit;
}

10. Mobile Number Validation

For a simple 10-digit mobile number validation:

$mobile = trim(
    $data['mobile'] ?? ''
);

if (!preg_match(
    '/^[0-9]{10}$/',
    $mobile
)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid mobile number"
    ]);

    exit;
}

The exact rule should match the application's supported phone-number format.

11. Minimum Length Validation

You can check whether a text value has enough characters.

$name = trim(
    $data['name'] ?? ''
);

if (strlen($name) < 3) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Name must contain at least 3 characters"
    ]);

    exit;
}

12. Maximum Length Validation

if (strlen($name) > 100) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Name is too long"
    ]);

    exit;
}

Length validation can help keep data within the limits expected by the application and database.

13. Numeric Validation

Suppose an API expects a numeric fee.

$fee = $data['fee'] ?? null;

if (!is_numeric($fee)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Fee must be numeric"
    ]);

    exit;
}

14. Positive Number Validation

$fee = $data['fee'] ?? null;

if (
    !is_numeric($fee) ||
    $fee < 0
) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Fee must be a valid positive value"
    ]);

    exit;
}

15. Validate Allowed Values

Some fields should accept only predefined values.

$status =
    $data['status'] ?? '';

$allowedStatus = [
    'active',
    'inactive'
];

if (!in_array(
    $status,
    $allowedStatus,
    true
)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid status"
    ]);

    exit;
}

16. Validate Password

A registration API can require a minimum password length.

$password =
    $data['password'] ?? '';

if (strlen($password) < 8) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Password must contain at least 8 characters"
    ]);

    exit;
}

Validation checks the password requirements. Password storage should still use secure password hashing.

17. Validate Password Confirmation

$password =
    $data['password'] ?? '';

$confirmPassword =
    $data['confirm_password'] ?? '';

if (
    $password !==
    $confirmPassword
) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Passwords do not match"
    ]);

    exit;
}

18. Validate Unique Email

Before registering a user, the API may check whether the email already exists.

$stmt = $pdo->prepare(
    "SELECT id
     FROM users
     WHERE email = ?
     LIMIT 1"
);

$stmt->execute([
    $email
]);

if ($stmt->fetch()) {

    http_response_code(409);

    echo json_encode([
        "success" => false,
        "message" =>
            "Email already exists"
    ]);

    exit;
}

19. Validation and HTTP Status Codes

Status Example
400 Invalid request structure
401 Authentication required
403 Not authorized
404 Requested resource not found
409 Duplicate/conflicting data
422 Validation failed
500 Server error

20. Return Validation Errors

A useful validation response should tell the client what went wrong.

{
    "success": false,
    "message": "Validation failed",
    "errors": {
        "name": "Name is required",
        "email": "Invalid email address"
    }
}

React Native can use the errors object to display messages next to the appropriate form fields.

21. Multiple Validation Errors

$errors = [];

if ($name === '') {

    $errors['name'] =
        "Name is required";
}

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    $errors['email'] =
        "Invalid email address";
}

if (!preg_match(
    '/^[0-9]{10}$/',
    $mobile
)) {

    $errors['mobile'] =
        "Invalid mobile number";
}

if (!empty($errors)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Validation failed",
        "errors" => $errors
    ]);

    exit;
}

22. Complete Registration Validation

<?php

header(
    "Content-Type: application/json"
);

require_once '../db.php';

$data = json_decode(
    file_get_contents("php://input"),
    true
);

if (!is_array($data)) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid JSON data"
    ]);

    exit;
}

$name = trim(
    $data['name'] ?? ''
);

$email = trim(
    $data['email'] ?? ''
);

$mobile = trim(
    $data['mobile'] ?? ''
);

$password =
    $data['password'] ?? '';

$errors = [];

if ($name === '') {

    $errors['name'] =
        "Name is required";

} elseif (strlen($name) < 3) {

    $errors['name'] =
        "Name must contain at least 3 characters";
}

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    $errors['email'] =
        "Invalid email address";
}

if (!preg_match(
    '/^[0-9]{10}$/',
    $mobile
)) {

    $errors['mobile'] =
        "Invalid mobile number";
}

if (strlen($password) < 8) {

    $errors['password'] =
        "Password must contain at least 8 characters";
}

if (!empty($errors)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Validation failed",
        "errors" => $errors
    ]);

    exit;
}

try {

    $stmt = $pdo->prepare(
        "SELECT id
         FROM users
         WHERE email = ?
         LIMIT 1"
    );

    $stmt->execute([
        $email
    ]);

    if ($stmt->fetch()) {

        http_response_code(409);

        echo json_encode([
            "success" => false,
            "message" =>
                "Email already exists"
        ]);

        exit;
    }

    $passwordHash =
        password_hash(
            $password,
            PASSWORD_DEFAULT
        );

    $stmt = $pdo->prepare(
        "INSERT INTO users
         (name, email, mobile, password)
         VALUES (?, ?, ?, ?)"
    );

    $stmt->execute([
        $name,
        $email,
        $mobile,
        $passwordHash
    ]);

    http_response_code(201);

    echo json_encode([
        "success" => true,
        "message" =>
            "Registration successful"
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" =>
            "Server error"
    ]);
}

?>

23. React Native Form Validation

React Native can perform basic validation before sending the request.

if (!name.trim()) {

    setError(
        "Name is required"
    );

    return;
}

if (!email.includes("@")) {

    setError(
        "Enter a valid email"
    );

    return;
}

Client-side validation provides quick feedback, but server-side validation is still required.

24. Display API Validation Errors

const response =
    await fetch(url, options);

const result =
    await response.json();

if (!response.ok) {

    setError(
        result.message
    );

    return;
}

The application can also display individual errors returned by the API.

25. Validation with Axios

try {

    const response =
        await axios.post(
            "https://example.com/api/register.php",
            {
                name,
                email,
                mobile,
                password
            }
        );

} catch (error) {

    if (
        error.response
    ) {

        console.log(
            error.response.data
        );
    }

}

26. Validation Before Database Insert

Request
   ↓
Parse JSON
   ↓
Validate Fields
   ↓
Check Duplicate Data
   ↓
Hash Password
   ↓
Database Insert
   ↓
JSON Response

Validation should happen before inserting or updating database records.

27. Validation and Security

  • Never trust client-side validation alone.
  • Validate all important server-side inputs.
  • Use prepared statements for database values.
  • Use password hashing for passwords.
  • Do not return database passwords in API responses.
  • Use authentication for protected APIs.
  • Validate uploaded files when file uploads are supported.
  • Use appropriate HTTP status codes.

28. Test Validation in Postman

Send an invalid registration request:

POST
http://localhost/api/register.php

Body:

{
    "name": "",
    "email": "wrong-email",
    "mobile": "123",
    "password": "123"
}

The API should reject the request and return validation errors instead of inserting invalid data.

29. Complete API Validation Flow

React Native Form
       ↓
Client Validation
       ↓
JSON Request
       ↓
PHP REST API
       ↓
Parse JSON
       ↓
Validate Fields
       ↓
Check Database Rules
       ↓
Valid?
   ↙        ↘
 Yes         No
  ↓           ↓
Database    422 Response
  ↓
JSON Success

30. API Validation Summary

API validation ensures that data received from React Native or another client satisfies the rules required by the server. PHP should validate the request, return useful validation errors, and only continue to the database when the input is valid.

Validate First
      ↓
Process Second
      ↓
Save Data Last

Good validation improves data quality, prevents invalid records, and helps create reliable REST APIs.

📌 Key Points

  • API validation checks incoming request data.
  • Server-side validation must always be performed.
  • Client-side validation improves user experience but cannot replace server validation.
  • Required fields should be checked.
  • Email, mobile, password, numeric, date, and length values can be validated.
  • Allowed values should be restricted using validation rules.
  • Duplicate records should be checked where required.
  • Validation errors can be returned using HTTP 422.
  • Multiple validation errors can be returned in an errors object.
  • Prepared statements should be used for database operations.
  • Passwords should be hashed before storage.
  • Postman can be used to test invalid and valid API requests.
  • The next lesson will cover API security.

🧠 Quick Quiz

Question: Where should important API validation always be performed?