First you can use the required
attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty()
on any variable ($_POST
or $_GET
):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset()
to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array()
:
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}