<?php
/**
* Form Field Formatter with Basic Validation
*
* This script formats form field data and performs basic validation.
*/
// Sample form data (replace with actual $_POST data)
$formData = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => '30',
'phone' => '123-456-7890',
'city' => 'New York',
];
/**
* Form Field Formatting Function
*
* Formats individual form fields for display or processing.
* @param string $fieldName The name of the form field.
* @param mixed $value The value of the form field.
* @param string $type The field type ('text', 'email', 'number', 'phone').
* @return string The formatted field value or an error message.
*/
function formatFormField(string $fieldName, $value, string $type): string
{
// Basic validation
if (empty($value)) {
return '<span style="color:red;">' . $fieldName . ' is required.</span>';
}
// Type-specific formatting
switch ($type) {
case 'text':
return '<input type="text" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
return '<span style="color:red;">' . $fieldName . ' is not a valid email.</span>';
}
return '<input type="email" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
case 'number':
if (!is_numeric($value)) {
return '<span style="color:red;">' . $fieldName . ' must be a number.</span>';
}
return '<input type="number" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
case 'phone':
// Basic phone number validation (can be improved)
if (!preg_match('/^\d{3}-\d{3}-\d{4}$/', $value)) {
return '<span style="color:red;">' . $fieldName . ' must be in the format XXX-XXX-XXXX.</span>';
}
return '<input type="tel" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">';
default:
return '<input type="text" name="' . $fieldName . '" value="' . htmlspecialchars($value) . '">'; // Default to text
}
}
// Output the formatted form fields
echo '<form>';
echo '<fieldset>';
echo '<legend>Form Data</legend>';
echo formatFormField('name', $formData['name'], 'text');
echo formatFormField('email', $formData['email'], 'email');
echo formatFormField('age', $formData['age'], 'number');
echo formatFormField('phone', $formData['phone'], 'phone');
echo formatFormField('city', $formData['city'], 'text');
echo '</fieldset>';
echo '<button type="submit">Submit</button>';
echo '</form>';
?>
Add your comment