<?php
/**
* Form Field Watcher and Validator
*
* Monitors form fields for changes and performs validation.
* Logs errors to a file.
*/
class FormWatcher {
private $form_data = [];
private $validation_rules = [];
private $log_file = 'form_validation.log';
public function __construct(array $validation_rules) {
$this->validation_rules = $validation_rules;
}
/**
* Registers a new form data field.
* @param string $name
* @param string $value
*/
public function registerField(string $name, string $value) {
$this->form_data[$name] = $value;
}
/**
* Validates the form data.
* @return array Array of errors. Empty array if no errors.
*/
public function validate() {
$errors = [];
foreach ($this->validation_rules as $field => $rule) {
$value = $this->form_data[$field] ?? ''; // Get value, default to empty string if not present
if ($rule['type'] === 'required' && empty($value)) {
$errors[] = $field . ': This field is required.';
} elseif ($rule['type'] === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[] = $field . ': Invalid email address.';
} elseif ($rule['type'] === 'min_length' && strlen($value) < $rule['length']) {
$errors[] = $field . ': Must be at least ' . $rule['length'] . ' characters.';
}
// Add more validation types here as needed.
}
return $errors;
}
/**
* Logs validation errors to a file.
* @param array $errors
*/
private function logErrors(array $errors) {
$log_message = date('Y-m-d H:i:s') . ' - Validation Errors:\n';
foreach ($errors as $error) {
$log_message .= $error . "\n";
}
file_put_contents($this->log_file, $log_message, FILE_APPEND);
}
/**
* Process form submission.
* @param array $post_data
*/
public function processSubmission(array $post_data) {
// Register form fields from the submitted data
foreach ($post_data as $key => $value) {
$this->registerField($key, $value);
}
// Validate the form data
$errors = $this->validate();
// Log any errors
if (!empty($errors)) {
$this->logErrors($errors);
} else {
// Form is valid, process the data
// ... your form processing logic here ...
echo "Form submitted successfully!\n";
}
}
}
// Example Usage:
// Define validation rules
$validation_rules = [
'name' => ['type' => 'required'],
'email' => ['type' => 'email'],
'message' => ['type' => 'min_length', 'length' => 10],
];
// Create a FormWatcher instance
$form_watcher = new FormWatcher($validation_rules);
// Simulate form submission
$form_data = $_POST; // Simulate form data from $_POST
// Process the form submission
$form_watcher->processSubmission($form_data);
?>
Add your comment