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.
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
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.
| 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 |
Common API validation rules include:
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;
}
$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;
}
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.
$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.
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;
}
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.
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;
}
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.
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;
}
$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;
}
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;
}
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.
$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;
}
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;
}
| 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 |
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.
$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;
}
<?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"
]);
}
?>
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.
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.
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
);
}
}
Request
↓
Parse JSON
↓
Validate Fields
↓
Check Duplicate Data
↓
Hash Password
↓
Database Insert
↓
JSON Response
Validation should happen before inserting or updating database records.
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.
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
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.
errors object.Question: Where should important API validation always be performed?