This question already has an answer here:
- PHP validation checkbox 3 answers
- How to validate single checkbox in php script 2 answers
- checkbox in PHP validation 2 answers
- How to validate a single checkbox using PHP & MySQL 2 answers
- PHP Checkbox Validation 3 answers
I have a problem with validating a checkbox. I want to show error message if "submit" is clicked while checkbox is unchecked. With the code I have right now, form gets submitted anyway. I've tried multiple code snippets I found from other questions but none seem to work..
HTML:
<?php include 'contact-form.php'; ?>
<form id="contact" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data">
<h3>Add issue</h3>
<fieldset>
<input placeholder="Nimi" type="text" tabindex="1" name="thename" value="<?= $thename ?>" autofocus>
<div class="error"><span><?= $name_error ?></span></div>
</fieldset>
<fieldset>
<input placeholder="Email" type="text" tabindex="2" name="email" value="<?= $email ?>">
<div class="error"><span><?= $email_error ?></span></div>
</fieldset>
<fieldset>
<input type="checkbox" name="checkbox1" value="yes"/> Annan ühendusele loa minu eluloo avaldamiseks siinsel kodulehel. <br>
<div class="error"><span><?= $checkbox1_error ?></span></div>
</fieldset>
</form>
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["thename"])) {
$name_error = "Palun sisesta nimi";
} else {
$thename = test_input($_POST["thename"]);
// check if name only contains letters, whitespace and hyphen
if (!preg_match("/^[a-zA-Z -]*$/",$thename)) {
$name_error = "Sisestada saab ainult tähti, tühikuid ja sidekriipse";
}
}
if (empty($_POST["email"])) {
$email_error = "Palun sisesta email";
} else {
$email = test_input($_POST["email"]);
// email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Sisesta email korrektselt";
}
}
if(!isset($_POST['checkbox1'])) {
//checkbox is not checked
$checkbox1_error = 'Väli peab olema kinnitatud';
}
if ($name_error == '' and $email_error == '' and $message_error == '' and $attachment_error == '' and $checkbox1_error == ''){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value
";
}
$to = 'myemail@gmail.com';
$subject = 'My subject';
$message = "My message";
if (@mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$email")){
$success = "Aitäh, kiri edukalt saadetud!";
} else {
$error = "Saatmine ebaõnnestus. Palun proovige uuesti.";
}
Any help is appreciated!
</div>