<?php
/**
* Data Migration Form Validation
*
* Validates form data for data migration purposes.
*
* @param array $data The form data array.
* @return array|bool Returns an array of errors if validation fails,
* or true if validation passes.
*/
function validateData(array $data)
{
$errors = [];
// Validate required fields
if (empty($data['firstName'])) {
$errors['firstName'] = 'First name is required.';
}
if (empty($data['lastName'])) {
$errors['lastName'] = 'Last name is required.';
}
if (empty($data['email'])) {
$errors['email'] = 'Email is required.';
}
if (empty($data['age'])) {
$errors['age'] = 'Age is required.';
}
// Validate email format
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email format.';
}
// Validate age is a number
if (!is_numeric($data['age'])) {
$errors['age'] = 'Age must be a number.';
}
if ($data['age'] < 0 || $data['age'] > 150) {
$errors['age'] = 'Age must be between 0 and 150.';
}
// Example: Validate first name length
if (strlen($data['firstName']) > 50) {
$errors['firstName'] = 'First name cannot be more than 50 characters.';
}
// Example: Validate last name length
if (strlen($data['lastName']) > 50) {
$errors['lastName'] = 'Last name cannot be more than 50 characters.';
}
// Return errors or success
if (!empty($errors)) {
return $errors;
} else {
return true; // Validation successful
}
}
//Example usage
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$formData = $_POST;
$validationErrors = validateData($formData);
if (is_array($validationErrors)) {
// Display errors to the user
echo "<div>";
foreach ($validationErrors as $field => $error) {
echo "<p style='color:red;'>$error</p>";
}
echo "</div>";
} else {
// Data is valid, proceed with migration
echo "Data is valid. Proceeding with migration...";
}
}
?>
Add your comment