PHP Class that validates form values
Put form fields into an array and state which validation methods to apply.
$fields = [
'username' => ['required', 'minlen' => 5, 'maxlen' => 15],
'email' => ['required', 'email'],
'password' => ['required', 'minlen' => 8],
'confirm_password' => ['required', 'match' => 'password'],
'age' => ['required', 'number'],
];The field is required and must not be empty.
Sets the minimum acceptable length of the field.
Sets the maximum acceptable length of the field.
Ensures the field value is an Email Address.
Validates that this field matches the same value as the field set in the match value.
Ensures the field value is a number.
Create a new object called $validator and use the $_POST array and previously declared $fields array to instantiate it. Set the $errors variable with any errors that may be thrown when validating the form.
$validator = new Validate($_POST, $fields);
$errors = $validator->validateForm();if (empty($errors)) {
echo "Form submitted successfully!";
} else {
foreach ($errors as $error) {
echo "<p>$error</p>";
}
}