1. <?php
  2. /**
  3. * Data Migration Form Validation
  4. *
  5. * Validates form data for data migration purposes.
  6. *
  7. * @param array $data The form data array.
  8. * @return array|bool Returns an array of errors if validation fails,
  9. * or true if validation passes.
  10. */
  11. function validateData(array $data)
  12. {
  13. $errors = [];
  14. // Validate required fields
  15. if (empty($data['firstName'])) {
  16. $errors['firstName'] = 'First name is required.';
  17. }
  18. if (empty($data['lastName'])) {
  19. $errors['lastName'] = 'Last name is required.';
  20. }
  21. if (empty($data['email'])) {
  22. $errors['email'] = 'Email is required.';
  23. }
  24. if (empty($data['age'])) {
  25. $errors['age'] = 'Age is required.';
  26. }
  27. // Validate email format
  28. if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
  29. $errors['email'] = 'Invalid email format.';
  30. }
  31. // Validate age is a number
  32. if (!is_numeric($data['age'])) {
  33. $errors['age'] = 'Age must be a number.';
  34. }
  35. if ($data['age'] < 0 || $data['age'] > 150) {
  36. $errors['age'] = 'Age must be between 0 and 150.';
  37. }
  38. // Example: Validate first name length
  39. if (strlen($data['firstName']) > 50) {
  40. $errors['firstName'] = 'First name cannot be more than 50 characters.';
  41. }
  42. // Example: Validate last name length
  43. if (strlen($data['lastName']) > 50) {
  44. $errors['lastName'] = 'Last name cannot be more than 50 characters.';
  45. }
  46. // Return errors or success
  47. if (!empty($errors)) {
  48. return $errors;
  49. } else {
  50. return true; // Validation successful
  51. }
  52. }
  53. //Example usage
  54. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  55. $formData = $_POST;
  56. $validationErrors = validateData($formData);
  57. if (is_array($validationErrors)) {
  58. // Display errors to the user
  59. echo "<div>";
  60. foreach ($validationErrors as $field => $error) {
  61. echo "<p style='color:red;'>$error</p>";
  62. }
  63. echo "</div>";
  64. } else {
  65. // Data is valid, proceed with migration
  66. echo "Data is valid. Proceeding with migration...";
  67. }
  68. }
  69. ?>

Add your comment