1. <?php
  2. /**
  3. * Form Field Formatter with Basic Validation
  4. *
  5. * This script formats form field data and performs basic validation.
  6. */
  7. // Sample form data (replace with actual $_POST data)
  8. $formData = [
  9. 'name' => 'John Doe',
  10. 'email' => 'john.doe@example.com',
  11. 'age' => '30',
  12. 'phone' => '123-456-7890',
  13. 'city' => 'New York',
  14. ];
  15. /**
  16. * Form Field Formatting Function
  17. *
  18. * Formats individual form fields for display or processing.
  19. * @param string $fieldName The name of the form field.
  20. * @param mixed $value The value of the form field.
  21. * @param string $type The field type ('text', 'email', 'number', 'phone').
  22. * @return string The formatted field value or an error message.
  23. */
  24. function formatFormField(string $fieldName, $value, string $type): string
  25. {
  26. // Basic validation
  27. if (empty($value)) {
  28. return '<span style="color:red;">' . $fieldName . ' is required.</span>';
  29. }
  30. // Type-specific formatting
  31. switch ($type) {
  32. case 'text':
  33. return '<input type="text" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
  34. case 'email':
  35. if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
  36. return '<span style="color:red;">' . $fieldName . ' is not a valid email.</span>';
  37. }
  38. return '<input type="email" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
  39. case 'number':
  40. if (!is_numeric($value)) {
  41. return '<span style="color:red;">' . $fieldName . ' must be a number.</span>';
  42. }
  43. return '<input type="number" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
  44. case 'phone':
  45. // Basic phone number validation (can be improved)
  46. if (!preg_match('/^\d{3}-\d{3}-\d{4}$/', $value)) {
  47. return '<span style="color:red;">' . $fieldName . ' must be in the format XXX-XXX-XXXX.</span>';
  48. }
  49. return '<input type="tel" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
  50. default:
  51. return '<input type="text" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">'; // Default to text
  52. }
  53. }
  54. // Output the formatted form fields
  55. echo '<form>';
  56. echo '<fieldset>';
  57. echo '<legend>Form Data</legend>';
  58. echo formatFormField('name', $formData['name'], 'text');
  59. echo formatFormField('email', $formData['email'], 'email');
  60. echo formatFormField('age', $formData['age'], 'number');
  61. echo formatFormField('phone', $formData['phone'], 'phone');
  62. echo formatFormField('city', $formData['city'], 'text');
  63. echo '</fieldset>';
  64. echo '<button type="submit">Submit</button>';
  65. echo '</form>';
  66. ?>

Add your comment