When a client sends data to a REST API, the server should not directly trust that data. Before storing or processing it, the API should validate the received values. In this lesson, we will learn how to validate student data before inserting it into MySQL.
Data validation means checking whether the data received by the API meets the required rules.
For example:
An API receives data from external clients such as React Native applications, web applications, and Postman. The server must verify this data before using it.
Client
↓
API
↓
Validate Data
↓
Database
Validation helps prevent invalid data from entering the database.
| Validation | Location |
|---|---|
| Client-side | React Native / Browser |
| Server-side | PHP REST API |
Client-side validation improves user experience, but server-side validation is essential because the server cannot assume that the client performed correct validation.
The API should validate data before executing an INSERT query.
JSON Request
↓
Decode JSON
↓
Validate Data
↓
INSERT INTO
↓
MySQL
This keeps invalid data away from the database.
First, read the JSON request body.
$data = json_decode(
file_get_contents("php://input"),
true
);
The JSON data is converted into a PHP associative array.
The API should make sure that decoded data is available before accessing its fields.
if (!is_array($data)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON data"
]);
exit;
}
Some fields may be required to create a student.
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
The values can now be checked individually.
A student's name should not be empty.
if ($name === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name is required"
]);
exit;
}
PHP provides filter_var() for validating email addresses.
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
An email field may contain an incorrectly formatted value.
For example:
Invalid:
rahul@
Valid:
rahul@example.com
The API should validate the format before accepting the value.
The mobile number can be checked according to the requirements of the application.
For example, a simple length check can be performed:
if ($mobile !== '' &&
strlen($mobile) < 10) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid mobile number"
]);
exit;
}
If the course is required, check that it is not empty.
if ($course === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Course is required"
]);
exit;
}
The trim() function removes unnecessary whitespace from the beginning and end of a string.
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
This helps prevent values containing only spaces from being treated as valid input.
You can validate the length of text values using strlen().
if (strlen($name) > 100) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name is too long"
]);
exit;
}
The maximum length should match the database column and application requirements.
When an API receives an ID, it should validate that the ID is an integer.
$id = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
This is useful for Get Single APIs.
An ID should normally be greater than zero.
if ($id === false || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid ID"
]);
exit;
}
The API can check whether the received JSON is valid.
$data = json_decode(
$input,
true
);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON"
]);
exit;
}
Multiple required fields can be validated together.
if (
$name === '' ||
$email === '' ||
$course === ''
) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Required fields are missing"
]);
exit;
}
A REST API should return a clear JSON response when validation fails.
{
"success": false,
"message": "Email is required"
}
The client can use this message to show an appropriate error.
HTTP status code 400 Bad Request can be used when the client sends invalid input.
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid input"
]);
<?php
header("Content-Type: application/json");
$input = file_get_contents("php://input");
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON"
]);
exit;
}
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
if ($name === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name is required"
]);
exit;
}
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email"
]);
exit;
}
if ($course === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Course is required"
]);
exit;
}
echo json_encode([
"success" => true,
"message" => "Validation successful"
]);
?>
Validation should happen before executing the INSERT query.
Receive JSON
↓
Decode JSON
↓
Validate
↓
Prepare SQL
↓
Execute INSERT
↓
Return Response
Never skip validation simply because the application already validates the data on the client side.
Validation and prepared statements solve different problems. Validation checks whether data is acceptable, while prepared statements safely pass values to SQL queries.
Validate Data
↓
Prepare SQL
↓
Execute Values
↓
Database
You can test validation by sending incomplete JSON from Postman.
{
"name": "Rahul"
}
If email and course are required, the API should reject this request and return a validation error.
Send an invalid email:
{
"name": "Rahul",
"email": "rahul@",
"course": "PHP"
}
The API should return a 400 response with an appropriate validation message.
Send valid data:
{
"name": "Rahul",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
The validation should pass and the API can continue to the database operation.
React Native can also validate form data before sending it to the API.
if (!name || !email) {
console.log("Required fields missing");
}
However, server-side validation should still be performed by PHP.
The rules should match the requirements of the API.
React Native
↓
JSON Request
↓
PHP API
↓
json_decode()
↓
Check JSON
↓
Validate Fields
↓
Prepared Statement
↓
MySQL
↓
JSON Response
This validation flow should be used whenever the API accepts user-provided data.
API validation protects the application from invalid input. PHP can check JSON syntax, required fields, email format, numeric values, string lengths, and other application rules before the data reaches MySQL.
Receive
↓
Decode
↓
Validate
↓
Process
↓
Database
↓
Response
Question: Which PHP function can be used to validate an email address?